wegelagerer
wegelagerer

Reputation: 3710

Default configuration for all HttpClient instances in .net Core

I have a scenario where I am configuring multiple HttpClient instances in Startup.cs which use same HttpClientHandlers. The only difference between those HttpClients is the BaseAddress property and the name of respective HttpClient instance since I'm using named HttpClients.

I was wondering if there is a possibility to create either a default HttpClient where I'd be adding all those handlers and then the named instances would inherit them or if there is some other way how can I centrally add those handlers without having to manually add them for each HttpClient instance.

private void ConfigureHttpClients(IServiceCollection services)
{
    services.AddHttpClient<IService1, Service>(client =>
    {
        client.BaseAddress = new Uri("http://api.test.com/");
    })
    .UseErrorHandling()
    .UseDefaultHeaders();

    services.AddHttpClient<IService2, Service2>(client =>
    {
        client.BaseAddress = new Uri("http://api.test-test.com/");
    })
    .UseErrorHandling()
    .UseDefaultHeaders();
}

Upvotes: 6

Views: 5020

Answers (3)

Master DJon
Master DJon

Reputation: 1965

If you don't use .NET 8, I am using .NET 7, you can use this to change the default HttpClient creation.

builder.Services.AddHttpClient(string.Empty).ConfigureHttpClient(c => c.BaseAddress = new Uri(baseUri));

Upvotes: 0

Ben Sampica
Ben Sampica

Reputation: 3402

There is now a .ConfigureHttpClientDefaults extension method in the Microsoft.Extensions.Http namespace.

Example

builder.Services.ConfigureHttpClientDefaults(); // has an overload for configuration.

Upvotes: 2

Fildor
Fildor

Reputation: 16104

An improvement for the situation could be an extensionmethod like this:

public static void AddMyHttpClient<TClient, TImplementation>( this IServiceCollection services, 
                                                              string baseUri ) 
{  
    services.AddHttpClient<TClient, TImplementation>(client => 
       { 
           client.BaseAddress = new Uri(baseUri); 
       })
       .UseErrorHandling()
       .UseDefaultHeaders();
}

which can then be used as

services.AddMyHttpClient<IService1, Service>("http://api.test.com/");

in Startup.cs


UPDATE

If the Lambda gets mistaken for a Func<HttpClient, TClient> you'll get a "Not all code paths return a value".

You can fix this like so:

var configureAction = (HttpClient client) => { client.BaseAddress = new Uri(baseUri); };
services.AddHttpClient<TClient, TImpl>(configureAction);

Seems strange, but I haven't found a better solution, yet.

Upvotes: 3

Related Questions