ASP Core HttpClientFactory Pattern Use Client Cert

Viewed 1597

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?
        });
2 Answers

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;
        });

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;
});
Related