我正在尝试从 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 就会得到结果,如果我等待一分钟左右的时间,再次仅第一次出现相同的错误。
小智 9
需要在创建发布请求之前设置安全协议类型。所以这:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
Run Code Online (Sandbox Code Playgroud)
应该出现在此之前:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
Run Code Online (Sandbox Code Playgroud)
因此,如果您看到它对后续请求起作用,则可能是您设置协议太晚了。
以下代码可用于帮助解决该问题。
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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23269 次 |
| 最近记录: |