In .NET applications, HttpClient is very well known class, and it is used for making HTTP requests from C# code. In this article, we will have a look HttpClient class and a middleware that can be used to get HttpClient instances for HTTP communication from C# code.
Each instance of HttpClient is a collection of settings applied to all requests executed by that instance. Every HttpClient instance uses its own connection pool, isolating its requests from requests executed by other HttpClient instances.
This class is recommended to be instantiated once in the application and it should be reused throughout the life of application.
If HttpClient class is instantiated for every requested, then it will exhaust the number of sockets available. This might result in deterioration of application performance (due to slower HTTP responses) and eventually application would start throwing SocketException errors.
So, this background is enough to proceed our discussion to the new middleware.
.NET provides a factory IHttpClientFactory, which can be used to create instances of HttpClient. This factory provides a central location for creating HttpClient instances and it also provides ability to configure logging experience for the HTTP communication.
One important facility provided by factory is, it provides a central location for configuring logical HttpClient instances.
So, let’s say the application needs to access APIs from two different sources, GitHub and Google maps APIs. The factory can be used to get one HttpClient instance for all GitHub API calls and the other HttpClient instance to make Google maps API calls.
This factory can be configured for an application via middleware.
Consuming the IHttpClientFactory is three step process:
- First step, use
AddHttpClientmiddleware to register the factory
- Second step, IHttpClientFactory can be injected in a class
- Third step, is to use CreateClient method to get HttpClient instance
Below sample code shows how to use this middleware. Note that every time a CreateClient method is called, it creates a new instance of HttpClient. Hence the caller of this method does have responsibility to cache the HttpClient instance (not shown in below demo).
|// Code for Startup.cs|
|public class Startup|
|// Some other code…|
|public void ConfigureServices(IServiceCollection services)|
|// AddHttpClient middleware to register IHttpClientFactory dependencies|
|public void Configure(IApplicationBuilder app, IWebHostEnvironment env)|
|// Configure request pipeline|
|// Some middlewares|
|// Code for HomeController.cs|
|public class HomeController : Controller|
|private readonly ILogger<HomeController> _logger;|
|private readonly IHttpClientFactory _clientFactory;|
|public HomeController(ILogger<HomeController> logger, IHttpClientFactory clientFactory)|
|_logger = logger;|
|_clientFactory = clientFactory;|
|public async Task<IActionResult> Index()|
|// Http Request|
|var request = new HttpRequestMessage(HttpMethod.Get,|
|// Http Headers|
|// Create HttpClient instance|
|var client = _clientFactory.CreateClient();|
|// HTTP API call|
|var response = await client.SendAsync(request);|
|// Handle Successful Response (or Error)|
|using var responseStream = await response.Content.ReadAsStreamAsync();|
|dynamic branches = await JsonSerializer.DeserializeAsync|
|// Error Handling|
This was basic usage scenario. In coming articles, we will see how to use named instances and typed instances of HttpClient using this middleware. Do you have any specific questions/suggestions ? Let me know your thoughts.