.Net Core HttpClientFactory 配置 HttpClientHandler

标签 .net asp.net-core .net-core

我目前正在配置我的 httpclientfactory这边走

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

};

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

要禁用安全证书的验证,但在执行太多请求时,我收到此异常:

Cannot access a disposed object. Object name: 'SocketsHttpHandler'.



我目前正在构建我的 httpclient这边走
HttpClient client = _httpClientFactory.CreateClient("ignoreSSL");

做测试,这个是这样解决的,不用httpclientfactory
HttpClient ad = new HttpClient(handler, false);

多我找我找不到怎么告诉httpclientfactory不让处理程序处理?

最佳答案

该问题是由于单个 HttpClientHandler 实例用于所有请求而引起的。管理、汇集和回收处理程序是 HttpClientFactory 的工作。

看起来实际的问题是如何在使用 HttpClientFactory 时禁用证书验证。这需要配置它使用的客户端处理程序。

As the documentation shows这是使用 ConfigurePrimaryHttpMessageHandler 完成的方法。从方法的注释:

Remarks

The delegate should return a new instance of the message handler each time it is invoked.



由该方法创建的处理程序将被添加到处理程序池中,并由其他处理程序(如 Polly 的重试处理程序)使用。 HttpClientFactory 将回收旧的处理程序来处理 DNS 注册更改。

代码应如下所示:
services.AddHttpClient<HttpWrapper>("ignoreSSL")
        .ConfigurePrimaryHttpMessageHandler(() =>
        {
            return new HttpClientHandler
            {
                ServerCertificateCustomValidationCallback = (m, crt, chn, e) => true
            };
        });

关于.Net Core HttpClientFactory 配置 HttpClientHandler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54256792/

相关文章:

c# - 为什么 Datetime.DayOfWeek 是错误的?

c# - Visual Studio 2013 项目引用另一个带有外部库的项目

c# - 从 HttpContext : where to put the code 获取 Razor Pages 中的用户名

linux - dotnet 命令找不到 .NET Core 2.1 的新安装

visual-studio - 在ASP.NET Core的stacktrace中包括文件名和行号

c# - 为什么 int 和 long 类型是一流的并且受到 C# 和运行时的青睐?

.net - DialogResult 关闭设置对通过 ShowDialog() 显示的表单有影响吗?

c# - NLog 环境变量配置文件

asp.net-core - 访问 IApplicationEnvironment.ApplicationBasePath

.net-core - 如何使用 xunit 和 moq 传递我的 DbContext 对象进行测试