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


当前回答

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

其他回答

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

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

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

这为我固定,添加网络服务的权限。 右键单击证书>所有任务>管理私钥…>添加…>添加“网络服务”。

在我的情况下,这个异常的根源是在代码的某些时候,下面的代码被调用:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;

这真的很糟糕。它不仅指示. net使用不安全的协议,而且还会影响在您的应用域中随后发出的每一个新的WebClient(和类似的)请求。(请注意,传入的web请求在你的ASP中不受影响。NET应用程序,但新的WebClient请求,如与外部web服务对话,是)。

在我的情况下,它实际上并不需要,所以我可以删除该语句,所有其他的web请求重新开始正常工作。根据我在其他地方的阅读,我了解到一些事情:

This is a global setting in your appdomain, and if you have concurrent activity, you can't reliably set it to one value, do your action, and then set it back. Another action may take place during that small window and be impacted. The correct setting is to leave it default. This allows .NET to continue to use whatever is the most secure default value as time goes on and you upgrade frameworks. Setting it to TLS12 (which is the most secure as of this writing) will work now but in 5 years may start causing mysterious problems. If you really need to set a value, you should consider doing it in a separate specialized application or appdomain and find a way to talk between it and your main pool. Because it's a single global value, trying to manage it within a busy app pool will only lead to trouble. This answer: https://stackoverflow.com/a/26754917/7656 provides a possible solution by way of a custom proxy. (Note I have not personally implemented it.)

如果客户端是一台windows机器,一个可能的原因可能是服务所需的tls或ssl协议未激活。

可以设置为:

控制面板->网络和Internet -> Internet选项->高级

向下滚动设置到“安全”,在两者之间进行选择

使用SSL 2.0 使用SSL 3.0 使用TLS 1.0协议 使用TLS 1.1 使用TLS 1.2