[英]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
。
返回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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.