问题
Any one know how to use client cert when using the HttpClientFactory? In all the examples I've found you need to provide an HttpMessageHandler in the HttpClient constructor, which isn't available when using the HttpClientFactory
services.AddHttpClient("NamedClient", client =>
{
var handler = new HttpClientHandler();
X509Certificate2 certificate = GetMyX509Certificate();
handler.ClientCertificates.Add(certificate);
client. // ?? How do I set the handler?
});
回答1:
I was able to get it working with help from @agua from mars
services.AddHttpClient("myservice", client =>
{
client.BaseAddress = new Uri("https://localhost:8717");
}).ConfigurePrimaryHttpMessageHandler(h =>
{
var handler = new HttpClientHandler();
handler.ClientCertificates.Add(GetCert());
return handler;
});
回答2:
You add a HttpMessageHandler in the http message handler pipeline using :
services.AddHttpMessageHandler<HttpClientHandler>()
And you register your handler using :
services.AddTransient(provider =>
{
var handler = new HttpClientHandler();
X509Certificate2 certificate = GetMyX509Certificate();
handler.ClientCertificates.Add(certificate);
return handler;
});
来源:https://stackoverflow.com/questions/52371768/asp-core-httpclientfactory-pattern-use-client-cert