How to use HttpClientFactory in ASP.NET Core
By FoxLearn 1/4/2025 3:00:08 AM 80
It also highlights that ASP.NET Core, introduced in version 2.1, is an open-source, cross-platform framework designed for building high-performance, modular web applications.
Understanding HttpClientFactory and Its Benefits
HttpClientFactory allows you to preconfigure named HttpClient
instances, providing a central location to register, configure, and use them in your application. HttpClient
, introduced in .NET Framework 4.5, is the most widely used method for making HTTP requests in .NET.
Creating multiple HttpClient
instances is inefficient because it leads to repeated reconnections to the remote server and can exhaust available sockets under heavy traffic. The recommended practice is to use a single shared HttpClient
instance to allow for connection reuse.
Even with a single shared HttpClient
instance, issues can arise, such as connections staying alive and ignoring DNS TTL settings. HttpClientFactory
addresses these problems by efficiently managing HttpClient
instances and handling the lifetime of HttpClientHandler
instances.
Getting started using HttpClientFactory in ASP.NET Core
To work with an application targeting .NET Core 2.1 in Visual Studio, you should have Visual Studio 2017 version 15.7 or later installed.
Creating a new ASP.NET Core 2.1 project in Visual Studio 2017.
Next, go to the Startup.cs
file to begin using HttpClientFactory
.
Using the HttpClientFactory
There are two ways to use HttpClientFactory
: NamedClient (default) and TypedClient.
Below is an example of using HttpClientFactory
as a NamedClient. The AddHttpClient
method is used in the ConfigureServices
method:
public void ConfigureServices(IServiceCollection services) { services.AddHttpClient("MyCustomApi", client => { client.BaseAddress = new Uri("https://localhost:5000/"); client.DefaultRequestHeaders.Add("Accept", "application/json"); client.DefaultRequestHeaders.Add("User-Agent", "MyApp"); }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); }
Alternatively, you can use HttpClientFactory
as a TypedClient. This involves creating custom classes and using dependency injection to inject HttpClient
.
services.AddHttpClient<MyCustomTypedClient>(client => client.BaseAddress = new Uri(Configuration["MyCustomTypedClientServiceUri"]));
Below is an example of a custom typed client, where HttpClient
is injected through the constructor:
public class CustomHttpClient { public HttpClient Client { get; } public CustomHttpClient(HttpClient client) { Client = client; } }
Finally, you can register this custom client in the ConfigureServices
method like this:
public void ConfigureServices(IServiceCollection services) { services.AddHttpClient<CustomHttpClient>(client => { client.BaseAddress = new Uri("https://localhost:5000/"); client.DefaultRequestHeaders.Add("Accept", "application/json"); }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); }
The custom type is passed as a generic argument to the AddHttpClient
method to register the typed client.
- Content Negotiation in Web API
- How to fix 'InvalidOperationException: Scheme already exists: Bearer'
- How to fix System.InvalidOperationException: Scheme already exists: Identity.Application
- Add Thread ID to the Log File using Serilog
- Handling Exceptions in .NET Core API with Middleware
- InProcess Hosting in ASP.NET Core
- Limits on ThreadPool.SetMinThreads and SetMaxThreads
- Controlling DateTime Format in JSON Output with JsonSerializerOptions