Consuming Web Services Using HTTP Clients and Getting Consumers

Now that we have built and tested our Northwind service, we will learn how to call it from any .NET app using the HttpClient class and its factory.

Understanding HttpClient

The easiest way to consume a web service is to use the HttpClient class. However, many people use it wrongly because it implements IDisposable , and Microsoft’s own documentation shows poor usage of it.

Usually, when a type implements IDisposable, we should create it inside a using statement to ensure it is disposed of as soon as possible. HttpClient is different because it is shared, reentrant, and partially thread-safe.

The problem has to do with how the underlying network sockets have to be managed. The bottom line is that we should use a single instance of it for each HTTP endpoint we consume during our application's life. This will allow each HttpClient instance to set defaults that are appropriate for the endpoint it works with while managing the underlying network sockets efficiently.

Configuring HTTP clients using HttpClientFactory

Microsoft is aware of the issue of .NET developers misusing HttpClient, and in ASP.NET Core 2.1, they introduced HttpClientFactory to encourage best practices, that is the technique we will use.

In the following example, we will use the Northwind MVC website as a client for the Northwind WebAPI service. Since both need to be hosted on a web server simultaneously, we first need to configure them to use different port numbers, as shown in the following list:

  • The Northwind Web API service will listen on port 5002 using HTTPS

  • The Northwind MVC website will continue to listen on port 5000 using HTTP and port 5001 using HTTPS

Let’s configure those ports:

Step 1: In the Northwind.WebApi project, in the Properties folder, in launchSettings.json, modify the applicationUrl setting of the https profile to use port 5002, as shown in the following code:

Get hands-on with 1400+ tech skills courses.