6.51Configuring IHttpClientBuilder
Created on Aug 17, 2026~1 min read
The .AddHttpClient(name, configure) method returns an IHttpClientBuilder instance, allowing further configuration, such as setting the HttpMessageHandler.
Example of Configuring Default and Specific Clients
// Configure the default clientservices.AddHttpClient(string.Empty, client => {}) .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { // Allow automatic redirects AllowAutoRedirect = true, // Use default credentials UseDefaultCredentials = true, // Enable cookies UseCookies = true, });// Configure the specific client named "weixin"services.AddHttpClient("weixin", client => {}) .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler());Uniformly Configuring All HttpClient Instances
In addition to configuring each client individually, you can also configure all HttpClient instances uniformly:
services.ConfigureHttpClientDefaults(clientBuilder =>{ clientBuilder.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler());});// Or use the IHttpRemoteBuilder extension method for one-click configurationservices.AddHttpRemote() .ConfigureHttpClientDefaults(clientBuilder => { clientBuilder.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler()); });This configuration approach makes the code more concise and modular, and easier to maintain and manage.