In frequently used code paths, such as controller actions, you should avoid using the HttpClient directly and opt for one of the IHttpClientFactory-based mechanisms instead. This way, you avoid wasting resources and creating performance overhead.
If a code path that creates and disposes of HttpClient objects is frequently used, then the following issues can occur:
The IHttpClientFactory was introduced in
ASP.NET Core 2.1 to solve these problems. It handles pooling HTTP connections to optimize performance and reliability.
There are several ways that you can use IHttpClientFactory in your application:
Alternatively, you may cache the HttpClient in a singleton or a static field. You should be aware that by default, the HttpClient doesn’t respect the DNS’s Time To Live (TTL) settings. If the IP address associated with a domain name changes, HttpClient might still use the old, cached IP address, leading to failed requests.
[ApiController]
[Route("controller")]
public class FooController : Controller
{
[HttpGet]
public async Task<string> Foo()
{
using var client = new HttpClient(); // Noncompliant
return await client.GetStringAsync(_url);
}
}
// File: Startup.cs
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient();
// ...
}
}
[ApiController]
[Route("controller")]
public class FooController : Controller
{
private readonly IHttpClientFactory _clientFactory;
public FooController(IHttpClientFactory clientFactory)
{
_clientFactory = clientFactory;
}
[HttpGet]
public async Task<string> Foo()
{
using var client = _clientFactory.CreateClient(); // Compliant (Basic usage)
return await client.GetStringAsync(_url);
}
}