7

我正在重写 WinForms 中的一些 Web 处理代码,并从 HttpWebRequest 切换到 HttpClient。我要求的最后一件事是我似乎无法找到如何完成。

在 HttpWebRequest 中,我可以从要连接的 Web 服务器捕获证书并显示它:

...
HttpWebRequest request = CreateHttpRequest(destUri);

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

cert = request.ServicePoint.Certificate;

if (cert != null) 
{ 
  cert2 = new X509Certificate2(cert); 
  X509Certificate2UI.DisplayCertificate(cert2);
}
...

我找不到使用 HttpClient 捕获证书的等效方法:

//... Use HttpClient.
using (HttpClient client = new HttpClient())
{
  using (HttpResponseMessage response = await client.GetAsync(destUri))
  {
    using (HttpContent content = response.Content)
    {
      string result = await content.ReadAsStringAsync();
    }
  }
}

我在这里如何/在哪里可以做到这一点?我不知道如何到达 ServicePoint.Certificate。

4

3 回答 3

5

显然,您不需要从 ServicePointManager.ServerCertificateValidationCallback 获取证书。您可以从 ServicepointManager 本身找到它,如下所示:

//... Use HttpClient.
using (HttpClient client = new HttpClient())
{
  using (HttpResponseMessage response = await client.GetAsync(destUri))
  {
    // Get Certificate Here
    var cert = ServicePointManager.FindServicePoint(destUri).Certificate;
    //
    using (HttpContent content = response.Content)
    {
      string result = await content.ReadAsStringAsync();
    }
  }
}
于 2017-07-14T16:08:21.513 回答
3

建立在 Remus 的答案上 - 这是我在 LinqPad 中拼凑的东西,它确实让您可以访问您的证书:

var handler = new WebRequestHandler();
handler.UseDefaultCredentials = true;
handler.AllowPipelining = true;
handler.ServerCertificateValidationCallback =  (sender, cert, chain, error) => {
    //do something with cert here
    cert.Subject.Dump();
    //useless validation on my part
    return true;
};


using (HttpClient client = new HttpClient(handler))
{
  using (HttpResponseMessage response = await client.GetAsync("https://google.com"))
  {
    using (HttpContent content = response.Content)
    {
        //foo
    }
  }
}

Dump()输出如下:

CN=*.google.com、O=Google Inc、L=Mountain View、S=California、C=US

CN=www.google.de, O=Google Inc, L=Mountain View, S=California, C=US

CN=www.google.com, O=Google Inc, L=Mountain View, S=California, C=US

于 2017-07-14T06:35:12.073 回答
2

将 aWebRequestHandler与适当的证书验证回调一起使用。例如,参见HttpClient、HttpClientHandler 和 WebRequestHandler 的解释

于 2017-07-14T06:19:36.520 回答