在默认注入的 IHttpClientFactory 中禁用 SSL 证书验证

Jan*_*ann 1 c# dependency-injection dotnet-httpclient asp.net-core

在 Startup.cs 中我注入一个IHttpClientFactory服务:

services.AddHttpClient();
Run Code Online (Sandbox Code Playgroud)

然后我可以创建一个新的HttpClient通过

public MyClass(IHttpClientFactory httpClientFactory, IOptions<MyClassOptions> options)
{
    _httpClient = httpClientFactory.CreateClient();
    // ...
}
Run Code Online (Sandbox Code Playgroud)

MyClass进行一些 API 访问;基本 URL 在对象中传递options

为了进行测试,我设置了 API 的虚拟实例,它使用自签名 SSL 证书。不幸的是,该证书被(正确地)识别为无效:

System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception.
 ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
Run Code Online (Sandbox Code Playgroud)

如何在工厂层(即直接在ConfigureServices方法中)禁用证书验证?

我发现了这个问题,但它似乎使用了一些自定义HttpClient实现(?),而我想针对默认实现。以下不起作用(DI 选择了错误的构造函数并随后失败):

services.AddHttpClient<IMyClass, MyClass>();
Run Code Online (Sandbox Code Playgroud)

这个答案建议为配置提供一个名称HttpClient,但它传递了一些魔术字符串,我想避免这种情况(MyClass位于设计为也可供其他人使用的类库中)。不传递名称也不起作用,因为AddHttpClient那样只会返回一个IServiceCollection对象。

Jan*_*ann 9

我现在想通了。我们可以应用这个答案来修改HttpMessageHandler默认值的主要部分HttpClient

services.AddHttpClient(Options.DefaultName, c =>
{
    // ...
}).ConfigurePrimaryHttpMessageHandler(() =>
{
    return new HttpClientHandler
    {
        ClientCertificateOptions = ClientCertificateOption.Manual,
        ServerCertificateCustomValidationCallback =
            (httpRequestMessage, cert, certChain, policyErrors) => true
    };
});
Run Code Online (Sandbox Code Playgroud)

每当注入默认值时,这都会生成HttpClient禁用 SSL 验证的对象。IHttpClientFactory