简体   繁体   English

.Net Core HttpClientFactory 配置 HttpClientHandler

[英].Net Core HttpClientFactory dispose HttpClientHandler

I am currently configuring my httpclientfactory this way我目前正在以这种方式配置我的httpclientfactory

HttpClientHandler httpClientHandler = new HttpClientHandler()
{
    ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; }

};

serviceCollection.AddHttpClient("ignoreSSL", c =>
{}).ConfigurePrimaryHttpMessageHandler(h => httpClientHandler);

To disable the validation of security certificates, but when doing too many requests I receive this exception:要禁用安全证书的验证,但在执行太多请求时,我收到此异常:

Cannot access a disposed object.无法访问已处置的对象。 Object name: 'SocketsHttpHandler'.对象名称:'SocketsHttpHandler'。

I currently build my httpclient this way我目前以这种方式构建我的httpclient

HttpClient client = _httpClientFactory.CreateClient("ignoreSSL");

Doing tests, this is solved in this way without httpclientfactory做测试,这个是这样解决的,不用httpclientfactory

HttpClient ad = new HttpClient(handler, false);

For more than I look for I can not find how to tell httpclientfactory not to make handler dispose?对于超过我寻找的我找不到如何告诉httpclientfactory不让处理程序处置?

The problem is caused because a single HttpClientHandler instance is used for all requests.该问题是由于单个HttpClientHandler 实例用于所有请求而引起的。 It's the HttpClientFactory's job to manage, pool and recycle handlers.管理、汇集和回收处理程序是 HttpClientFactory 的工作。

It looks like the actual question is how to disable certificate validation when using HttpClientFactory.看起来实际的问题是如何在使用 HttpClientFactory 时禁用证书验证。 This requires configuring the client handlers used by it.这需要配置它使用的客户端处理程序。

As the documentation shows this is done using the ConfigurePrimaryHttpMessageHandler method. 正如文档所示,这是使用ConfigurePrimaryHttpMessageHandler方法完成的。 From the method's remarks :从方法的注释:

Remarks评论

The delegate should return a new instance of the message handler each time it is invoked.每次调用时,委托都应返回消息处理程序的新实例。

The handlers created by that method will be added to a handler pool and used by other handlers like Polly's retry handlers.由该方法创建的处理程序将被添加到处理程序池中,并由其他处理程序(如 Polly 的重试处理程序)使用。 HttpClientFactory will recycle older handlers to handle DNS registration changes. HttpClientFactory 将回收旧的处理程序来处理 DNS 注册更改。

The code should look like this:代码应如下所示:

services.AddHttpClient<HttpWrapper>("ignoreSSL")
        .ConfigurePrimaryHttpMessageHandler(() =>
        {
            return new HttpClientHandler
            {
                ServerCertificateCustomValidationCallback = (m, crt, chn, e) => true
            };
        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM