如何在 .NET Core 中使用 HttpClientHandler 和 HttpClientFactory [英] How to use HttpClientHandler with HttpClientFactory in .NET Core
问题描述
我想使用 .NET Core 2.1 中可用的 HttpClientFactory
但我也想使用 HttpClientHandler
来利用 AutomaticDecompression
创建 HttpClients
时的属性.
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
.
我很挣扎,因为 .AddHttpMessageHandler<>
需要一个 DelegatingHandler
而不是 HttpClientHandler
.
I am struggling because the .AddHttpMessageHandler<>
takes a DelegatingHandler
not a HttpClientHandler
.
有谁知道如何让它发挥作用?
Does anyone know how to get this to work?
谢谢,吉姆
推荐答案
其实我不是用自动解压的,但是实现的方法是正确注册http客户端
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>())
这篇关于如何在 .NET Core 中使用 HttpClientHandler 和 HttpClientFactory的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!