由于以下错误消息,我们无法使用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。这会改变什么吗?
After days of pulling what hair I have left out, we solved the problem. I tried everything suggested on this post and nothing worked for me. For us, we had a basic .Net Framework 4.8 console app running on a customers Windows VM. The on-premise server we were communicating with required that SSL Certificate Validation was turned off. One of our guys discovered that the server required we were using TLS 1.0 and on the registry settings of the VM, TLS 1.0 was disabled. Once we enabled that, it worked. I also needed to added the following two lines as mentioned many times above:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
这个问题可以有很多答案,因为它是关于一个通用的错误消息。我们在一些服务器上遇到了这个问题,但在开发机器上没有。拔了大部分头发后,我们发现这是微软的一个漏洞。
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>
添加在另一个答案中已经提到的注册表设置。
所有这些都在我发布的知识库文章中提到过。