ASP Core HttpClientFactory Pattern Use Client Cert

纵饮孤独 提交于 2020-01-02 05:26:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!