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

时间:2019-04-19 11:35:36

标签: c#

我正在尝试通过Web API使用客户端的Web服务,以下是我们当前用于绕过SSL证书的代码

ServicePointManager.ServerCertificateValidationCallback + =(发送方,证书,链,sslPolicyErrors)=> true;

运行良好,直到他们从一开始就禁用了TLS 1.0和TLS 1.1。现在,我们添加了以下代码以将TLS 1.2用于客户端服务器连接

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; ServicePointManager.ServerCertificateValidationCallback + =(发送方,证书,链,sslPolicyErrors)=> true;

现在,我收到“请求已中止:无法创建SSL / TLS安全通道。”仅当我第一次点击该API时才出错,而如果我连续点击该API则要获取结果,如果我等待大约一分钟左右的时间,则仅第一次遇到相同的错误。

3 个答案:

答案 0 :(得分:1)

以下代码可用于帮助解决问题。

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;
}

答案 1 :(得分:1)

需要在创建发布请求之前完成安全协议类型的设置。所以这个:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

应在此之前出现:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

因此,如果您发现它可用于后续请求,则可能是您设置协议的时间太晚。

答案 2 :(得分:0)

对于运行.NET版本4的用户,可以在下面使用

ServicePointManager.SecurityProtocol = CType(768, SecurityProtocolType) Or CType(3072,SecurityProtocolType)
ServicePointManager.Expect100Continue = True