How to work with HttpClientFactory in ASP.Net Core

Take advantage of HttpClientFactory to manage HttpClient instances efficiently

How to work with HttpClientFactory in ASP.Net Core
Thinkstock

ASP.Net Core is an open source, cross-platform, lean, and modular framework for building high-performance web applications, introduced in ASP.Net Core 2.1.

This article explains HttpClientFactory and how you can work with it in ASP.Net Core.

What is HttpClientFactory and why you should use it

You can take advantage of HttpClientFactory to preconfigure named HttpClient instances. Note that the HttpClientFactory is a central location that can be used to register, configure, and consume HttpClient instances that your application might need. (Incidentally, the HttpClient was introduced in .Net Framework 4.5 and is the most popular way to consume HTTP requests in .Net.)

Creating too many HttpClient instances is inefficient because your application would need to bear the cost of reconnecting to the remote server whenever a new client needs to connect to it. Another problem in creating multiple HttpClient instances—tat is, creating a new HttpClient instance for every request that your application needs to process—is that the available sockets might get exhausted when there is heavy traffic. The recommended practice is to create a single shared HttpClient instance so the connections can be reused.

However, even if you use a single shared HttpClient instance, there are problems galore. One is that the connections are kept alive and so will not respect the DNS Time to Live (TTL) settings. HttpClientFactory solves the problems discussed above. The HttpClientFactory is designed to manage HttpClient instances efficiently; it can manage the lifetime of the HttpClientHandler instances.

Getting started using HttpClientFactory in ASP.Net Core

Getting started with HttpClientFactory is easy. To work with an application in Visual Studio that targets .Net Core 2.1, you should have Visual Studio 2017 15.7 or later installed in your system. Although you can use .Net Core 2.1 in Visual Studio 20017 15.6, there are some known issues.

Assuming that you’re running Visual Studio 2017 and that .Net Core 2.1 is already installed in your system, follow these steps to create an ASP.Net Core project in Visual Studio 2017:

  1. In the Visual Studio IDE, choose File > New > Project.
  2. Choose ASP.Net Core Web Application (.Net Core) from the list of the templates displayed.
  3. Specify a name for the project.
  4. Click OK to save the project.
  5. Select API in the New .Net Core Web Application window.
  6. Choose ASP.Net Core 2.1 from the dropdown list at the top.
  7. Uncheck the Enable Docker Support checkbox.
  8. Select No Authentication because you won’t be using authentication in this example.
  9. Click OK.

This creates a new ASP.Net Core 2.1 Project in Visual Studio 2017.

Now, head over to the Startup.cs file and start using HttpClientFactory as described in the next section.

Using the HttpClientFactory

There are two ways in which you can use HttpClientFactory: NamedClient (this is the default) and TypedClient.

The following code snippet illustrates how you can use the HttpClientFactory as a NamedClient. Note how the AddHttpClient method has been used in the ConfigureServices method.

public void ConfigureServices(IServiceCollection services)
        {
            services.AddHttpClient("IDGCustomApi", client =>
            {
                client.BaseAddress = new Uri("https://localhost:6045/");
                client.DefaultRequestHeaders.Add("Accept", "application/json");
                client.DefaultRequestHeaders.Add("User-Agent", "IDG");
            });
services.AddMvc().SetCompatibilityVersion
(CompatibilityVersion.Version_2_1);
        }

You can also use HttpClientFactory as a TypedClient. In this case, you can define custom classes and then take advantage of dependency injection to inject HttpClient. Basically, you can register a custom typed client as shown in the code snippet below.

services.AddHttpClient<YourCustomTypedClient>(client => 
client.BaseAddress = new Uri(Configuration["YourCustomTypedClientServiceUri"]));

The following code snippet illustrates a custom typed client. Note how the HttpClient instance has been injected via the constructor.

public class CustomHttpClient
    {
        public HttpClient Client { get; }
        public CustomHttpClient(HttpClient client)
        {
            Client = client;
        }
    }

You can register this custom client in the ConfigureServices method as shown in the code snippet below. Note how the custom type has been passed as a generic argument to the AddHttpClient method.

public void ConfigureServices(IServiceCollection services)
        {
            services.AddHttpClient<CustomHttpClient>(client =>
            {
                client.BaseAddress = new Uri("https://localhost:6045/");
                client.DefaultRequestHeaders.Add("Accept", "application/json");
            });
          services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

Copyright © 2018 IDG Communications, Inc.

How to choose a low-code development platform