【问题标题】:Accessing HttpClientHandler in the same place as HttpClient is created在创建 HttpClient 的地方访问 HttpClientHandler
【发布时间】: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


【解决方案1】:

Reddit 的某人suggested 以下解决方案。一旦调用了AddHttpClient,就不能再修改HttpClientHandler。不过可以共享资源:

var certificates= new ConcurrentDictionary<string, X509Certificate2>();
services.AddSingleton(certificates);
services
    .AddHttpClient("sslclient", x =>
    {
        ...
    })
    .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
    {
        ServerCertificateCustomValidationCallback = (request, certificate, chain, errors) =>
        {
            certificates.TryAdd(request.RequestUri.Host, new X509Certificate2(certificate));
            return true;
        }
    });

在发出 HTTP 请求的代码中,您还需要注入 certificates 字典。提出请求后,您可以在字典中查找证书:

var response = await httpClient.GetAsync(url);
if (certificates.ContainsKey(uri.Host))
{
    // Happy days!
}

【讨论】:

  • Thomas,我也处于同样的困境中,将旧的 .NET Framework 移植到 core 2.x+ 中的首选 http 客户端被证明很有趣。在我的情况下,它是对 cookie 容器的访问。伟大的大灯泡熄灭了你提到的容器。发布答案后有什么需要注意的吗?
  • 不确定我是否理解这个问题?您想访问使用 HttpClient 的 cookie 容器吗?
  • 正确。我想标准化 HttpClientFactory 的使用和返回的各种风格的 httpclient。
  • 我不知道你会如何使用 HttpClient 来做到这一点。也许创建一个新问题?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-25
相关资源
最近更新 更多