“请求被中止:无法创建 SSL/TLS 安全通道”第一次访问 API 时

我正在尝试从 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 会得到结果,如果我等待大约一分钟左右的时间,再次仅在第一次访问时出现相同的错误。


森栏
浏览 334回答 3
3回答

精慕HU

设置安全协议类型需要在创建发布请求之前完成。所以这:ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;应该出现在这之前:HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);因此,如果您看到它对后续请求有效,则可能是您设置协议的时间太晚了。

慕盖茨4494581

以下代码可用于帮助解决问题。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;}

慕尼黑5688855

对于运行 .NET 版本 4 的用户,他们可以使用下面的ServicePointManager.SecurityProtocol = CType(768, SecurityProtocolType) Or CType(3072,SecurityProtocolType)ServicePointManager.Expect100Continue = True
打开App,查看更多内容
随时随地看视频慕课网APP