Problem

How to consume ASP.NET Core Web API using HttpClient.

Solution

We’ll create a library to wrap the functionality of HttpClient. I’ll use builder pattern for this purpose. Add a class with methods for storing the parts of HttpClient.

  1. public class HttpRequestBuilder
  2. {
  3. private HttpMethod method = null;
  4. private string requestUri = "";
  5. private HttpContent content = null;
  6. private string bearerToken = "";
  7. private string acceptHeader = "application/json";
  8. private TimeSpan timeout = new TimeSpan(0, 0, 15);
  9. public HttpRequestBuilder()
  10. {
  11. }
  12. public HttpRequestBuilder AddMethod(HttpMethod method)
  13. {
  14. this.method = method;
  15. return this;
  16. }
  17. public HttpRequestBuilder AddRequestUri(string requestUri)
  18. {
  19. this.requestUri = requestUri;
  20. return this;
  21. }
  22. public HttpRequestBuilder AddContent(HttpContent content)
  23. {
  24. this.content = content;
  25. return this;
  26. }
  27. public HttpRequestBuilder AddBearerToken(string bearerToken)
  28. {
  29. this.bearerToken = bearerToken;
  30. return this;
  31. }
  32. public HttpRequestBuilder AddAcceptHeader(string acceptHeader)
  33. {
  34. this.acceptHeader = acceptHeader;
  35. return this;
  36. }
  37. public HttpRequestBuilder AddTimeout(TimeSpan timeout)
  38. {
  39. this.timeout = timeout;
  40. return this;
  41. }
  42. rest of code

Add a method to send a request using HttpClient and get the response.

We’ll also add a factory class to build requests for GET, POST, PUT, PATCH, and DELETE.

JsonContent, PatchContent, and FileContent are custom classes to simplify the sending of data.

Finally, a few extension methods to help working with HttpResponseMessage class.

We can use the code above like -

Here is how the sample client looks like.


Note
The sample code has examples of another type of requests too. It uses CRUD API created in a previous post. Download its project and run the API before running this console sample.

Source Code

GitHub