由于以下错误消息,我们无法使用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; };

其他回答

我终于找到了答案(我没有注明我的来源,但它来自一次搜索);

虽然代码在Windows XP中工作,但在Windows 7中,你必须在开头添加这个:

// using System.Net;
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
// Use SecurityProtocolType.Ssl3 if needed for compatibility reasons

现在,它工作得很完美。


齿顶高

Robin French提到过;如果你在配置PayPal时遇到了这个问题,请注意从2018年12月3日开始他们将不支持SSL3。您需要使用TLS。这是关于它的Paypal页面。

另一种可能是正在执行的代码没有所需的权限。

在我的例子中,我在使用Visual Studio调试器测试对web服务的调用时得到了这个错误。Visual Studio没有以管理员身份运行,这导致了此异常。

我一整天都在为这个问题而挣扎。

当我用。net 4.5创建一个新项目时,我终于让它工作了。

但如果我降级到4.0,我又遇到了同样的问题,而且对于那个项目来说是不可逆转的(即使我试图再次升级到4.5)。

奇怪的是,没有其他错误消息,但“请求被中止:无法创建SSL/TLS安全通道。

如果您是从Visual Studio运行代码,请尝试以管理员身份运行Visual Studio。为我修正了这个问题。

默认的。net ServicePointManager。SecurityProtocol使用SSLv3和TLS协议。如果您正在访问Apache服务器,有一个名为SSLProtocol的配置变量,默认为TLSv1.2。您可以设置ServicePointManager。使用您的web服务器支持的适当协议或更改您的Apache配置以允许所有协议,如SSLProtocolall。