17

Is there a way to add a handler to all clients created by the IHttpClientFactory? I know you can do the following on named clients:

services.AddHttpClient("named", c =>
{
    c.BaseAddress = new Uri("TODO");
    c.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    c.DefaultRequestHeaders.CacheControl = new CacheControlHeaderValue
    {
        NoCache = true,
        NoStore = true,
        MaxAge = new TimeSpan(0),
        MustRevalidate = true
    };
}).ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
{
    AllowAutoRedirect = false,
    AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip
});

But I don't want to use named clients I just want to add a handler to all clients that are given back to me via:

clientFactory.CreateClient();
Kirk Larkin
  • 73,173
  • 13
  • 183
  • 186
Hawkzey
  • 977
  • 10
  • 18

1 Answers1

18

When you use CreateClient with no parameters, you implicitly request a named client, where the name is Options.DefaultName (string.Empty). To affect this default instance, specify Options.DefaultName when calling AddHttpClient:

services.AddHttpClient(Options.DefaultName, c =>
{
    // ...
}).ConfigurePrimaryHttpMessageHandler(() =>
{
    // ...
});

Tobias J notes in the comments that the API docs for AddHttpClient states the following:

Use DefaultName as the name to configure the default client.

Kirk Larkin
  • 73,173
  • 13
  • 183
  • 186
  • 2
    @janw the [documentation](https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.httpclientfactoryservicecollectionextensions.addhttpclient?view=dotnet-plat-ext-3.1#Microsoft_Extensions_DependencyInjection_HttpClientFactoryServiceCollectionExtensions_AddHttpClient_Microsoft_Extensions_DependencyInjection_IServiceCollection_System_String_) for the `AddHttpClient` overloads which take a name parameter specify that `Options.DefaultName` is indeed used as the default name. – Tobias J Aug 21 '20 at 13:30
  • Anyone figure out a way to do this with typed clients? Doesn't seem to work for those – Sinaesthetic Nov 27 '21 at 21:47