Consuming ASP.NET Core 2.0 Web API using HttpClient


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


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 parts of HttpClient:

Add a method to send request using HttpClient and return 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 class to simplify sending of data:

Finally 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: sample code has examples of other type of requests too.

Note: sample code uses CRUD API created in a previous post. Download it’s project and run the API before running this console sample.

Source Code



    1. private void EnsureArguments()
      if (this.method == null)
      throw new ArgumentNullException(“Method”);

      if (string.IsNullOrEmpty(this.requestUri))
      throw new ArgumentNullException(“Request Uri”);

Leave a Reply