gpt4 book ai didi

c# - 如何将 httpclienthandler 显式传递给 httpclientfactory?

转载 作者:行者123 更新时间:2023-11-30 22:53:47 33 4
gpt4 key购买 nike

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

如有任何帮助,我们将不胜感激。

最佳答案

假设您的意思是使用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 被注入(inject)并调用客户端时,就是这种方式。

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

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

关于c# - 如何将 httpclienthandler 显式传递给 httpclientfactory?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56850413/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com