A named client centralizes the configuration for an HttpClient that calls a particular remote API. Register it with IHttpClientFactory under a case-sensitive string name, then request configured instances wherever they are needed. The factory manages the underlying handler pipeline, avoiding socket exhaustion and helping clients respect DNS changes. section 33.2.2 section 33.5
A rates client
Register a client named "rates" with a BaseAddress and a default User-Agent header. Application code can then call factory.CreateClient("rates") and request the relative URL "latest" without repeating that setup. A name such as "Rates" refers to a different client, while an unregistered name produces an unconfigured client. section 33.2.2
Listing 33.4 Using IHttpClientFactory to create a named HttpClient
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Services.AddHttpClient("rates", (HttpClient client) => #1
{
client.BaseAddress = #2
new Uri("https://example.com/rates/"); #2
client.DefaultRequestHeaders.Add( #2
HeaderNames.UserAgent, "ExchangeRateViewer"); #2
})
.ConfigureHttpClient((HttpClient client) => {}) #3
.ConfigureHttpClient(
(IServiceProvider provider, HttpClient client) => {}); #4
WebApplication app = builder.Build();
app.MapGet("/", async (IHttpClientFactory factory) => #5
{
HttpClient client = factory.CreateClient("rates"); #6
var response = await client.GetAsync("latest"); #7
#7
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
});
app.Run();
#1 Provides a name for the client and a configuration function
#2 The configuration function runs every time the named HttpClient is requested.
#3 You can add more configuration functions for the named client, which run in sequence.
#4 Additional overloads exist that allow access to the DI container when creating a named client.
#5 Injects the IHttpClientFactory using DI
#6 Requests the configured named client called “rates”
#7 Uses the HttpClient the same way as before
The listing shows registration-time configuration, optional additional configuration functions, factory lookup, and an outgoing request. section 33.2.2
Use the pattern in a small sequence:
- Register each remote API with a meaningful string name and configure its base address and default headers in one place. section 33.2.2
- Inject IHttpClientFactory into the consuming service or endpoint and call CreateClient with the exact registered name. section 33.2.2
- Add handlers to the named client when every request needs cross-cutting behavior such as authentication, logging, metrics, or API-key headers. section 33.4
- Keep in mind that named clients centralize HTTP configuration but still leave raw request URLs and response parsing in consuming code; typed clients can encapsulate that behavior further. section 33.2.2
