I thought of using HttpClientFactory but I need to attach the certificate while making a call Currently, I am using HttpClient, But don't know how to attach the certificate.
Below is the httpClient code:
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)
};
So, how to convert the above httpClient to HttpClientFactory?
Any help would be appreciated.
Assuming you mean by using ServiceCollection
, You can configure the handler when setting up the client
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;
});
That way when IHttpClientFactory
is injected and the client is called.
var _client = httpClientFactory.CreateClient("MyClient");
the created client will have the desired certificates already configured.