在默认注入的 IHttpClientFactory 中禁用 SSL 证书验证
Disable SSL certificate verification in default injected IHttpClientFactory
在Startup.cs中我注入了一个IHttpClientFactory
服务:
services.AddHttpClient();
然后我可以通过
创建一个新的HttpClient
public MyClass(IHttpClientFactory httpClientFactory, IOptions<MyClassOptions> options)
{
_httpClient = httpClientFactory.CreateClient();
// ...
}
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.
如何在工厂层禁用证书验证,即直接在 ConfigureServices
方法中?
我找到了 ,但它似乎使用了一些自定义 HttpClient
实现(?),而我想针对默认实现。以下不起作用(DI 选择了错误的构造函数并随后失败):
services.AddHttpClient<IMyClass, MyClass>();
建议为配置的 HttpClient
提供一个名称,但它传递了一些我想避免的魔术字符串(MyClass
位于 class 设计为其他人也可以使用的库)。不传递名称也不起作用,因为 AddHttpClient
然后只是 returns 一个 IServiceCollection
对象。
我现在明白了。我们可以应用修改默认HttpClient
的主HttpMessageHandler
:
services.AddHttpClient(Options.DefaultName, c =>
{
// ...
}).ConfigurePrimaryHttpMessageHandler(() =>
{
return new HttpClientHandler
{
ClientCertificateOptions = ClientCertificateOption.Manual,
ServerCertificateCustomValidationCallback =
(httpRequestMessage, cert, certChain, policyErrors) => true
};
});
只要注入默认 IHttpClientFactory
,这将产生 HttpClient
个禁用 SSL 验证的对象。
在Startup.cs中我注入了一个IHttpClientFactory
服务:
services.AddHttpClient();
然后我可以通过
创建一个新的HttpClient
public MyClass(IHttpClientFactory httpClientFactory, IOptions<MyClassOptions> options)
{
_httpClient = httpClientFactory.CreateClient();
// ...
}
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.
如何在工厂层禁用证书验证,即直接在 ConfigureServices
方法中?
我找到了 HttpClient
实现(?),而我想针对默认实现。以下不起作用(DI 选择了错误的构造函数并随后失败):
services.AddHttpClient<IMyClass, MyClass>();
HttpClient
提供一个名称,但它传递了一些我想避免的魔术字符串(MyClass
位于 class 设计为其他人也可以使用的库)。不传递名称也不起作用,因为 AddHttpClient
然后只是 returns 一个 IServiceCollection
对象。
我现在明白了。我们可以应用HttpClient
的主HttpMessageHandler
:
services.AddHttpClient(Options.DefaultName, c =>
{
// ...
}).ConfigurePrimaryHttpMessageHandler(() =>
{
return new HttpClientHandler
{
ClientCertificateOptions = ClientCertificateOption.Manual,
ServerCertificateCustomValidationCallback =
(httpRequestMessage, cert, certChain, policyErrors) => true
};
});
只要注入默认 IHttpClientFactory
,这将产生 HttpClient
个禁用 SSL 验证的对象。