由于以下错误消息,我们无法使用WebRequest连接到HTTPS服务器:

请求被中止:无法创建SSL/TLS安全通道。

我们知道服务器没有有效的HTTPS证书,但为了绕过这个问题,我们使用下面的代码,我们从另一个StackOverflow帖子:

private void Somewhere() {
    ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(AlwaysGoodCertificate);
}

private static bool AlwaysGoodCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors) {
   return true;
}

问题是服务器从未验证证书,并出现上述错误而失败。有人知道我该怎么做吗?


我应该提到的是,我和一个同事几周前进行了测试,它运行得很好,与我上面写的类似。我们发现的唯一“主要区别”是,我用的是Windows 7,而他用的是Windows XP。这会改变什么吗?


当前回答

In my case, I was running under Visual Studio 2022. Time and time again I was getting this error. Going through the code I saw that it retrieved the certificate just fine. Security was set to TLS1.2, both answers above. For whatever reason, running Visual Studio as Administrator made it work! Maybe someone can explain to me how the code retrieved the certificate from the store just fine. I could see it and all the properties. Why in the name of this world would it not process the request unless I run VS in admin mode???

其他回答

这个错误是一般的,有很多原因导致SSL/TLS协商失败。最常见的是无效或过期的服务器证书,您可以通过提供自己的服务器证书验证钩子来解决这个问题,但这并不一定是唯一的原因。服务器可能需要相互身份验证,它可能配置了一组客户端不支持的密码,它可能有太大的时间漂移,以至于握手无法成功,还有很多其他原因。

最好的解决方案是使用channel故障排除工具集。channnel是负责SSL和TLS的SSPI提供者,您的客户端将使用它进行握手。看看TLS/SSL工具和设置。

另请参阅如何启用通道事件日志记录。

这个问题可以有很多答案,因为它是关于一个通用的错误消息。我们在一些服务器上遇到了这个问题,但在开发机器上没有。拔了大部分头发后,我们发现这是微软的一个漏洞。

https://support.microsoft.com/en-us/help/4458166/applications-that-rely-on-tls-1-2-strong-encryption-experience-connect

从本质上讲,MS假定您想要较弱的加密,但操作系统被修补为只允许TLS 1.2,因此您会收到可怕的“请求被中止:无法创建SSL/TLS安全通道”。

有三个解决办法。

用适当的更新修补操作系统:http://www.catalog.update.microsoft.com/Search.aspx?q=kb4458166 在app.config/web中添加一个设置。配置文件(如上链接所述):

    <runtime>
       <AppContextSwitchOverrides value="Switch.System.Net.DontEnableSchUseStrongCrypto=false" />
    </runtime>

添加在另一个答案中已经提到的注册表设置。

所有这些都在我发布的知识库文章中提到过。

我在仓库和档案里都有证书。我试图连接文件,得到这个错误消息。我在店里用的那台还能用。我的最佳猜测是,当我想使用文件中的证书时,由于存储了证书而导致了某种冲突。 (同一台机器上的另一个服务使用存储中的证书,而我已经使用文件中的证书开发了一个不同的服务。直到测试之前,在开发过程中都非常有效)。

确保ServicePointManager设置是在创建HttpWebRequest之前完成的,否则它将无法工作。

工作原理:

ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
       | SecurityProtocolType.Tls11
       | SecurityProtocolType.Tls12
       | SecurityProtocolType.Ssl3;

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://google.com/api/")

失败:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://google.com/api/")

ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
       | SecurityProtocolType.Tls11
       | SecurityProtocolType.Tls12
       | SecurityProtocolType.Ssl3;

这样做帮助了我:

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;