Jed*_*Jed 4 c# ssl certificate httpclient
有人可以告诉我为什么这会引发证书无效的错误吗?在 中PowerShell,当我使用 IP 地址Invoke-WebRequest并设置主机标头以匹配证书中的 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);
Run Code Online (Sandbox Code Playgroud)
错误:
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.
Run Code Online (Sandbox Code Playgroud)
此代码是监控实用程序的一部分,我们需要能够探测负载均衡器后面的每个 Web 前端。我们经常使用 PowerShell 执行此操作,只要我设置主机标头以匹配证书,我就从未见过此问题。
HttpClient 中的默认行为是在证书有任何问题时抛出错误。
如果您想绕过此行为,您可以将代码更改为:
using 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;
}
};
using var spClient = new HttpClient(spHandler);
spClient.BaseAddress = new Uri("https://10.0.0.24");
using var spRequest = new HttpRequestMessage(HttpMethod.Get, "/api/controller/");
spRequest.Headers.Host = "somehost.com";
using var spResponse = await spClient.SendAsync(spRequest);
Run Code Online (Sandbox Code Playgroud)
所有的Console.WriteLine东西只是你看到的证书信息,你可以在了解发生了什么后将其删除。
这return true就是绕过证书问题的方法。
在生产中使用它时要小心,最好的解决方案是检查证书问题。
| 归档时间: |
|
| 查看次数: |
4597 次 |
| 最近记录: |