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.

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

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now