簡體   English   中英

如何在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

返回IHttpClientBuilderAddHttpClient方法使您可以訪問配置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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM