BV *_*oya 5 c# .net-core httpclientfactory
我想过使用 HttpClientFactory 但我需要在拨打电话时附加证书目前,我正在使用 HttpClient,但不知道如何附加证书。
下面是httpClient代码:
HttpClientHandler httpClientHandler = new HttpClientHandler
{
SslProtocols = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12,
ClientCertificateOptions = ClientCertificateOption.Manual
};
httpClientHandler.ClientCertificates.Add(CertHelper.GetCertFromStoreByThumbPrint(_Settings.MtlsThumbPrint, StoreName.My, _Settings.IgnoreCertValidChecking));
httpClientHandler.ServerCertificateCustomValidationCallback = OnServerCertificateValidation;
HttpClient _client = new HttpClient(httpClientHandler)
{
Timeout = TimeSpan.FromMinutes(1),
BaseAddress = new Uri(_Settings.BaseUrl)
};
Run Code Online (Sandbox Code Playgroud)
那么,如何将上面的httpClient转换为HttpClientFactory呢?
任何帮助,将不胜感激。
假设您的意思是使用ServiceCollection
,您可以在设置客户端时配置处理程序
services.AddHttpClient("MyClient", client => {
client.Timeout = TimeSpan.FromMinutes(1),
client.BaseAddress = new Uri(_Settings.BaseUrl)
})
.ConfigurePrimaryHttpMessageHandler(() => {
var httpClientHandler = new HttpClientHandler
{
SslProtocols = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12,
ClientCertificateOptions = ClientCertificateOption.Manual
};
httpClientHandler.ClientCertificates.Add(CertHelper.GetCertFromStoreByThumbPrint(_Settings.MtlsThumbPrint, StoreName.My, _Settings.IgnoreCertValidChecking));
httpClientHandler.ServerCertificateCustomValidationCallback = OnServerCertificateValidation;
return httpClientHandler;
});
Run Code Online (Sandbox Code Playgroud)
这样,什么时候IHttpClientFactory
注入并调用客户端。
var _client = httpClientFactory.CreateClient("MyClient");
Run Code Online (Sandbox Code Playgroud)
创建的客户端将具有已配置的所需证书。
归档时间: |
|
查看次数: |
4335 次 |
最近记录: |