我试图从Web API使用客户端的Web服务,下面是我们目前用来绕过SSL证书的代码
ServicePointManager.ServerCertificateValidationCallback + =(sender,cert,chain,sslPolicyErrors)=> true;
它工作正常,直到他们从最后禁用TLS 1.0和TLS 1.1。现在我们添加了以下代码,以便将TLS 1.2用于客户端服务器连接
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; ServicePointManager.ServerCertificateValidationCallback + =(sender,cert,chain,sslPolicyErrors)=> true;
现在我收到“请求被中止:无法创建SSL / TLS安全通道。”仅当我第一次点击API时出错,然后在我不断点击API时获得结果,如果我等待一段时间,如果一分钟左右,再次第一次出现相同的错误。
以下代码可用于帮助解决问题。
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
ServicePointManager.ServerCertificateValidationCallback += ValidateServerCertificate;
...
private static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
// If the certificate is a valid, signed certificate, return true to short circuit any add'l processing.
if (sslPolicyErrors == SslPolicyErrors.None)
{
return true;
}
else
{
// cast cert as v2 in order to expose thumbprint prop - if needed
var requestCertificate = (X509Certificate2)certificate;
// init string builder for creating a long log entry
var logEntry = new StringBuilder();
// capture initial info for the log entry
logEntry.AppendFormat("SSL Policy Error(s): {0} - Cert Issuer: {1} - SubjectName: {2}",
sslPolicyErrors.ToString(),
requestCertificate.Issuer,
requestCertificate.SubjectName.Name);
// check for other error types as needed
if (sslPolicyErrors == SslPolicyErrors.RemoteCertificateChainErrors) //Root CA problem
{
// check chain status and log
if (chain != null && chain.ChainStatus != null)
{
// check errors in chain and add to log entry
foreach (var chainStatus in chain.ChainStatus)
{
logEntry.AppendFormat("|Chain Status: {0} - {1}", chainStatus.Status.ToString(), chainStatus.StatusInformation.Trim());
}
}
}
// replace with your logger
MyLogger.Info(logEntry.ToString().Trim());
}
return false;
}