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


当前回答

只要这是一个相对“活”的链接,我想我会添加一个新的选项。这种可能性是由于Poodle攻击的问题,该服务不再支持SSL 3.0。看看关于这个的谷歌语句。我在使用多个web服务时同时遇到了这个问题,并意识到一定发生了什么事情。我切换到TLS 1.2,一切都恢复正常了。

http://googleonlinesecurity.blogspot.com/2014/10/this-poodle-bites-exploiting-ssl-30.html

其他回答

这样做帮助了我:

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

我们在Windows Server 2012R2客户端中遇到了同样的问题。 错误40表示客户端和服务器不同意使用密码套件。 在大多数情况下,服务器需要客户端无法识别的密码套件。

如果你不能修改服务器设置,解决方案是将那些“缺失”的密码套件添加到客户端:

First, go to SSLLabs SSL Labs Enter the url of the site/api you are having problem to connect Wait a few minutes until the test is completed Go to 'Cipher Suites' section and read very carefully TLS 1.3 / TLS 1.2 There you will find the Cipher Suites accepted by the server Now in your windows server, go to Regedit Open the Key: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Cryptography\Configuration\Local\SSL There you will find 2 folders: 00010002 -->TLS 1.2 and 00010003 --> TLS 1.3 Now, edit the Functions key, and add the suites required by the server In our case, we needed to Add TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 to 00010002 folder

另一种可能是箱子上的证书输入不当。请确保选中周围的复选框。最初我没有这样做,所以代码要么超时,要么抛出相同的异常,因为私钥无法定位。

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

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>

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

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

正如你所知道的,有很多原因可能会发生这种情况。我想我应该加上我遇到的原因…

如果你设置了WebRequest的值。Timeout到0,这是抛出的异常。下面是我的代码…(只是超时值不是硬编码的0,而是一个被无意中设置为0的参数)。

WebRequest webRequest = WebRequest.Create(@"https://myservice/path");
webRequest.ContentType = "text/html";
webRequest.Method = "POST";
string body = "...";
byte[] bytes = Encoding.ASCII.GetBytes(body);
webRequest.ContentLength = bytes.Length;
var os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
os.Close();
webRequest.Timeout = 0; //setting the timeout to 0 causes the request to fail
WebResponse webResponse = webRequest.GetResponse(); //Exception thrown here ...