Search code examples
c#.net-coredotnet-httpclient.net-core-2.1httpclientfactory

How to use HttpClientHandler with HttpClientFactory in .NET Core


I want to use the HttpClientFactory that is available in .NET Core 2.1 but I also want to use the HttpClientHandler to utilize the AutomaticDecompression property when creating HttpClients.

I am struggling because the .AddHttpMessageHandler<> takes a DelegatingHandler not a HttpClientHandler.

Does anyone know how to get this to work?

Thanks, Jim


Solution

  • Actually I'm not using automatic decompression but the way to achieve this is to properly register http client

    services.AddHttpClient<MyCustomHttpClient>()
       .ConfigureHttpMessageHandlerBuilder((c) =>
         new HttpClientHandler()
         {
            AutomaticDecompression = System.Net.DecompressionMethods.GZip
         }
       )
       .AddHttpMessageHandler((s) => s.GetService<MyCustomDelegatingHandler>())