首页 > 解决方案 > ASP.NET Core 2.1:将客户端证书添加到已注册的类型化 HTTP 客户端

问题描述

我介绍了 ASP.NET Core 2.1 的新方法,以在我的应用程序中创建/注册 HTTP 客户端,如此处所述。在我需要将客户端证书添加到我键入的 HTTP 客户端之前,它运行良好。

我做了很多研究,但我没有找到方法。

我期待这样的事情:

services.AddHttpClient<IMonitoringService, MonitoringService>(
            client =>
            {
                client.BaseAddress = new Uri(this.Configuration.GetSection("ServiceEndpoints:Monitoring").Get<ServiceEndpointConfiguration>().Endpoint);
                client.ClientCertificates.Add(new X509Certificate2(/* ... */)); // Error: `ClientCertificates` doesn't exists.
            });

或者像这样:

services.AddHttpClient<IMonitoringService, MonitoringService>(
                client => client.BaseAddress = new Uri(this.Configuration.GetSection("ServiceEndpoints:Monitoring").Get<ServiceEndpointConfiguration>().Endpoint))
            .AddHttpMessageHandler(
                () =>
                {
                    var handler = new HttpClientHandler();
                    handler.ClientCertificates.Add(new X509Certificate2(/* ... */));
                    return handler; // Error: Expected return type is `DelegatingHandler`.
                });

但是这样的方式不存在..

有没有办法做到这一点?

标签: c#asp.netasp.net-coredotnet-httpclient

解决方案


您的经验是正确的,因为此函数用于扩展请求管道,AddHttpMessageHandler因此需要返回一种类型。DelegatingHandler为了创建HttpClientHandler附加了客户端证书的,您应该改为使用ConfigurePrimaryHttpMessageHandler创建并返回配置的HttpClientHandler.


推荐阅读