【发布时间】:2019-08-28 09:59:52
【问题描述】:
我有一项服务请求 URL 并验证服务器 SSL 证书。代码已经在完整的 .NET 框架中使用 HttpWebRequest 顺利运行,但现在我想将其迁移到 HttpClient 和 .NET Core。我可以像这样拿到证书(多篇博文和堆栈溢出答案都推荐这种方法):
X509Certificate2 cert = null;
var httpClient = new HttpClient(new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (request, certificate, chain, errors) =>
{
cert = certificate;
return true;
}
});
httpClient.GetAsync(...);
这里的问题是我不断创建新的HttpClient 实例,不推荐这样做。我想移动到HttpClientFactory,为什么我在我的设置代码中添加以下内容:
services
.AddHttpClient("sslclient", x =>
{
...
})
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (request, certificate, chain, errors) =>
{
return true;
}
});
现在的挑战是代码创建客户端不再有权访问ServerCertificateCustomValidationCallback:
var httpClient = httpClientFactory.CreateClient("sslclient");
有人知道怎么解决吗?
【问题讨论】:
-
也许我的回答here对你有帮助。
-
我不这么认为。您仅在控制器中使用 HttpClient 来发出请求。我的挑战是我想在控制器中获取回调。
标签: .net-core dotnet-httpclient