我正在使用 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 overwritten in 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/