4

我想使用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 呢?

任何帮助,将不胜感激。

4

1 回答 1

6

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

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

于 2019-07-02T11:43:55.893 回答