Search code examples
c#.net-coredotnet-httpclientasp.net-core-3.1

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();
}

Solution

  • 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.