如何将httpclienthandler显式传递给httpclientfactory?

时间:2019-07-02 10:27:40

标签: 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)
};

那么,如何将上面的httpClient转换为HttpClientFactory?

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

假设您的意思是使用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;
});

那样,当注入IHttpClientFactory并调用客户端时。

var _client = httpClientFactory.CreateClient("MyClient");

创建的客户端将已经配置了所需的证书。