How to use HttpClientHandler with HttpClientFactor

2019-04-23 13:54发布

问题:

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

回答1:

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