如何在 core2.1 中使用 WinHttpHandler 和 IHttpClientFactory?
How to use WinHttpHandler with IHttpClientFactory in core2.1?
我正在尝试将新的 IHttpClientFactory
与 ASP.net Core 2.1 WEB API 应用程序一起使用。
public void ConfigureServices(IServiceCollection services)
{
// other services configuration
services.AddHttpClient();
}
在我的 ConfigureServices
方法中,我看不到添加 IHttpClientFactory
并将其配置为使用 WinHttpHandler
.
的方法
return 和 IHttpClientBuilder
的 AddHttpClient
方法使您可以访问配置 HttpMessageHandler
的方法,但这些方法必须派生自 DelegatingHandler
但是WinHttpHandler
不派生自 DelegatingHandler
.
在构建时无法告诉 HttpClient
使用 WinHttpHandler
。
想通了。
感谢@Nkosi 在评论中的提示!
我通过在注册 HttpClient
服务时使用命名 HttpClient
解决了这个问题,然后将消息处理程序配置为使用 WinHttpHandler
作为 PrimaryHandler
services.AddHttpClient<HttpClient>("WinHttp")
.ConfigureHttpMessageHandlerBuilder(c =>
{
c.PrimaryHandler = new WinHttpHandler() { WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy };
});
然后在使用IHttpClientFactory
时,请指定您在注册时提供的名称。
var httpClient = this._httpClientFactory.CreateClient("WinHttp");
您的 HttpClient
现在将使用 WinHttpHandler
!
注意
要使用 WinHttpHandler,您必须添加 nuget 包 System.Net.Http.WinHttpHandler
我正在尝试将新的 IHttpClientFactory
与 ASP.net Core 2.1 WEB API 应用程序一起使用。
public void ConfigureServices(IServiceCollection services)
{
// other services configuration
services.AddHttpClient();
}
在我的 ConfigureServices
方法中,我看不到添加 IHttpClientFactory
并将其配置为使用 WinHttpHandler
.
return 和 IHttpClientBuilder
的 AddHttpClient
方法使您可以访问配置 HttpMessageHandler
的方法,但这些方法必须派生自 DelegatingHandler
但是WinHttpHandler
不派生自 DelegatingHandler
.
在构建时无法告诉 HttpClient
使用 WinHttpHandler
。
想通了。
感谢@Nkosi 在评论中的提示!
我通过在注册 HttpClient
服务时使用命名 HttpClient
解决了这个问题,然后将消息处理程序配置为使用 WinHttpHandler
作为 PrimaryHandler
services.AddHttpClient<HttpClient>("WinHttp")
.ConfigureHttpMessageHandlerBuilder(c =>
{
c.PrimaryHandler = new WinHttpHandler() { WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy };
});
然后在使用IHttpClientFactory
时,请指定您在注册时提供的名称。
var httpClient = this._httpClientFactory.CreateClient("WinHttp");
您的 HttpClient
现在将使用 WinHttpHandler
!
注意 要使用 WinHttpHandler,您必须添加 nuget 包 System.Net.Http.WinHttpHandler