【问题标题】:How to use WinHttpHandler with IHttpClientFactory in core2.1?如何在core2.1中使用WinHttpHandler和IHttpClientFactory?
【发布时间】:2018-06-08 13:47:05
【问题描述】:

我正在尝试将新的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。

【问题讨论】:

  • 检查最近提出的类似问题stackoverflow.com/questions/50747749/… 根据我在构建器源代码中阅读的内容,建议的答案有保证。
  • 不是我需要的,但很接近,请参阅下面的答案。
  • 好吧,我认为它会引导您朝着正确的方向前进。很高兴你想出来了。编码愉快。

标签: c# asp.net-core asp.net-core-2.1


【解决方案1】:

想通了。

感谢@Nkosi 在 cmets 中提供的提示!

我在注册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

【讨论】:

    猜你喜欢
    • 2022-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-21
    • 2022-10-02
    相关资源
    最近更新 更多