允许所有证书的做法非常强大,但也可能存在风险。如果您只想允许有效证书以及某些特定证书,可以按照以下方式操作。
.NET Core:
using (var httpClientHandler = new HttpClientHandler())
{
httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, sslPolicyErrors) =>
{
if (sslPolicyErrors == SslPolicyErrors.None)
{
return true;
}
if (cert.GetCertHashString() == "99E92D8447AEF30483B1D7527812C9B7B3A915A7")
{
return true;
}
return false;
};
using (var httpClient = new HttpClient(httpClientHandler))
{
var httpResponse = httpClient.GetAsync("https://example.com").Result;
}
}
.NET Framework:
System.Net.ServicePointManager.ServerCertificateValidationCallback += delegate (
object sender,
X509Certificate cert,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None)
{
return true;
}
if (cert.GetCertHashString() == "99E92D8447AEF30483B1D7527812C9B7B3A915A7")
{
return true;
}
return false;
};
更新:
如何在 Chrome 中获取 cert.GetCertHashString()
的值:
点击地址栏中的 Secure
或 Not Secure
。
![](https://istack.dev59.com/0H3Su.webp)
![](https://istack.dev59.com/7bPur.webp)
然后点击证书 -> 详细信息 -> 指纹并复制该值。记得使用 cert.GetCertHashString().ToLower()
。
![](https://istack.dev59.com/1j8so.webp)