由于以下错误消息,我们无法使用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。这会改变什么吗?


当前回答

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

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>

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

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

其他回答

我也有同样的问题,发现这个答案对我很有效。密码是3072。此链接提供了关于“3072”修复的详细信息。

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

XmlReader r = XmlReader.Create(url);
SyndicationFeed albums = SyndicationFeed.Load(r);

在我的情况下,有两个提要需要修复:

https://www.fbi.gov/feeds/fbi-in-the-news/atom.xml
https://www.wired.com/feed/category/gear/latest/rss

我在Windows 2008服务器上的. net 4.5.2 Winform应用程序上得到了相同的错误。

我尝试了以下修复方法:

ServicePointManager。SecurityProtocol = SecurityProtocolType. tls1 |安全协议类型。Tls11 | SecurityProtocolType.Tls12;

但这并没有起作用,错误的发生次数仍然存在。

根据上面的答案之一,是否必须覆盖注册表的SchUseStrongCrypto键。如果我设置这个键会有什么副作用吗?

Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001

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???

这些答案都不适合我,谷歌chrome和邮递员工作,握手服务器,但ie和。net不工作。在谷歌chrome在安全选项卡>连接显示加密和认证使用ECDHE_RSA与P-256和AES_256_GCM密码套件与服务器握手。

我在windows server 2012 R2上安装了IIS密码和密码套件列表,无法找到带有P-256和AES_256_GCM密码套件的ECDHE_RSA。然后我把Windows更新到上一个版本,但问题没有解决。最后在搜索之后,我明白了windows server 2012 R2不支持GSM,并将我的服务器更新到windows server 2016,我的问题解决了。

这样做帮助了我:

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