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

标签 c# .net-core

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

相关文章:

c# - HttpRequestException - 1&1 Ionos 计划上的 SendGrid 电子邮件 API v3 集成

c# - serilog 格式 SourceContext 仅显示程序集名称

c# - 使用 Protractor 的 C# 单元测试中的无效操作异常

c# - Expression<Func<T1, T2>> 变量能否可靠地用作字典中的键?

c# - 让 EF Linq Select 语句选择常量或函数

c# - 重构switch语句

c# - 通过将状态存储到作用域局部变量中来避免关闭快速路径

c# - MVC 异步 Controller Action

c# - 如何在 ASP.NET Core 中注册单例工厂解析作用域对象?

c# - 在 linq 中将字符串转换为 int 求和