c# - 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`.
});
但是这样的方式不存在..
有没有办法做到这一点?
解决方案
您的经验是正确的,因为此函数用于扩展请求管道,AddHttpMessageHandler
因此需要返回一种类型。DelegatingHandler
为了创建HttpClientHandler
附加了客户端证书的,您应该改为使用ConfigurePrimaryHttpMessageHandler
创建并返回配置的HttpClientHandler
.
推荐阅读
- java - 为什么HashMap中的loadFactor默认设置为0.75?
- mysql - 分组和加入
- linux - (后缀 + dovecot + noIP)554 5.7.1 - 中继访问被拒绝
- python - 用于 Rest API 自动化测试的 Python 中的放心等价物
- c# - Xamarin Forms:防止条目焦点上的自动滚动
- r - 如何计算r中非线性最小二乘的置信区间?
- sql - 使用字符串的一部分作为变量?
- autodesk-forge - 如何停止从 Viewer3D.js 向 Mixpanel 发送数据的 HTTP 请求
- java - 如何向在 Android 应用程序中创建的此电子邮件添加超链接?
- cassandra - 错误:备份期间发生此错误:[Errno 1] Unknown host Traceback(最近一次调用最后一次):