HttpClient证书错误

时间:2017-11-30 17:42:04

标签: c# ssl certificate httpclient

有人可以告诉我为什么这会导致证书无效的错误?在PowerShell中,当我在Invoke-WebRequest中使用IP地址并将主机头设置为与证书中的CN匹配时,我不会收到证书错误。我会假设HttpClient会是一样的吗?

var spHandler = new HttpClientHandler();
var spClient = new HttpClient(spHandler);
spClient.BaseAddress = new Uri("https://10.0.0.24");
var spRequest = new HttpRequestMessage(HttpMethod.Get, "/api/controller/");
spRequest.Headers.Host = "somehost.com";
var spResponse = await spClient.SendAsync(spRequest);

错误:

WebException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
AuthenticationException: The remote certificate is invalid according to the validation procedure.

此代码是监视器实用程序的一部分,我们需要能够探测负载均衡器后面的每个Web前端。我们使用PowerShell做了很多事情,只要我设置Host标头以匹配证书,我就没见过这个问题。

1 个答案:

答案 0 :(得分:1)

HttpClient中的默认行为是在证书出现问题时抛出错误。

如果您想绕过此行为,可以将代码更改为:

var spHandler = new HttpClientHandler()
{
  ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) =>
  {
    Console.WriteLine($"Sender: {sender}");
    Console.WriteLine($"cert: {cert}");
    Console.WriteLine($"chain: {chain}");
    Console.WriteLine($"sslPolicyErrors: {sslPolicyErrors}");
    return true;
  }
};

var spClient = new HttpClient(spHandler);
spClient.BaseAddress = new Uri("https://10.0.0.24");
var spRequest = new HttpRequestMessage(HttpMethod.Get, "/api/controller/");
spRequest.Headers.Host = "somehost.com";
var spResponse = await spClient.SendAsync(spRequest);

所有Console.WriteLine内容只是您要查看证书信息,您可以在了解了正在发生的事情后删除它。

return true是绕过证书问题的。

小心在生产中使用它,最好的解决方案是检查证书问题。