gpt4 book ai didi

c# - 如何从 Microsoft.Extensions.Http 包中配置 HttpClient?

转载 作者:行者123 更新时间:2023-12-04 08:41:22 25 4
gpt4 key购买 nike

我正在使用 Microsoft.Extensions.Http我的 .NET Core 项目的包。向 API 发送请求时,我必须停用证书验证。不幸的是,我不知道在哪里为此配置客户端。设置 DI 容器时,我试过这个

private static IServiceCollection ConfigureHttpClients(this IServiceCollection services)
{
services.AddHttpClient<IMyInterface, MyImplementation>(httpClient =>
{
using HttpClientHandler httpClientHandler = new HttpClientHandler()
{
ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
};
httpClient = new HttpClient(httpClientHandler);
});

// ...

return services;
}
但这不起作用,我的 IDE 向我显示了变量 httpClient 的信息。

the value passed to the method is never used because it is overwrittenin the method body before being read


那么我必须在哪里配置客户端以禁用验证?

最佳答案

使用 ConfigurePrimaryHttpMessageHandler配置类型化客户端使用的处理程序

//...

services
.AddHttpClient<IMyInterface, MyImplementation>()
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler() {
ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
});

//...
引用 Configure the HttpMessageHandler

关于c# - 如何从 Microsoft.Extensions.Http 包中配置 HttpClient?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64551350/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com