Consuming ASP.NET Core 2.0 Web API Using HttpClient

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.   
  10.       public HttpRequestBuilder()  
  11.       {  
  12.       }  
  13.   
  14.       public HttpRequestBuilder AddMethod(HttpMethod method)  
  15.       {  
  16.           this.method = method;  
  17.           return this;  
  18.       }  
  19.         
  20.       public HttpRequestBuilder AddRequestUri(string requestUri)  
  21.       {  
  22.           this.requestUri = requestUri;  
  23.           return this;  
  24.       }  
  25.   
  26.       public HttpRequestBuilder AddContent(HttpContent content)  
  27.       {  
  28.           this.content = content;  
  29.           return this;  
  30.       }  
  31.   
  32.       public HttpRequestBuilder AddBearerToken(string bearerToken)  
  33.       {  
  34.           this.bearerToken = bearerToken;  
  35.           return this;  
  36.       }  
  37.   
  38.       public HttpRequestBuilder AddAcceptHeader(string acceptHeader)  
  39.       {  
  40.           this.acceptHeader = acceptHeader;  
  41.           return this;  
  42.       }  
  43.   
  44.       public HttpRequestBuilder AddTimeout(TimeSpan timeout)  
  45.       {  
  46.           this.timeout = timeout;  
  47.           return this;  
  48.       }  
  49.  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