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


当前回答

如果服务器对HTTP请求返回HTTP 401未授权响应,则会出现“请求已终止:无法创建SSL/TLS安全通道”异常。

您可以通过打开跟踪级系统来确定是否发生这种情况。Net日志记录用于客户端应用程序,如本回答中所述。

一旦日志配置就绪,运行应用程序并重现错误,然后在日志输出中查找如下一行:

System.Net Information: 0 : [9840] Connection#62912200 - Received status line: Version=1.1, StatusCode=401, StatusDescription=Unauthorized.

在我的情况下,我未能设置服务器所期望的特定cookie,导致服务器以401错误响应请求,从而导致“无法创建SSL/TLS安全通道”异常。

其他回答

您可以尝试安装演示证书(一些ssl提供程序提供一个月的免费演示证书),以确定问题是否与证书有效性有关。

以上大多数答案都提到了会话算法或密钥交换算法。

在我的情况下,两者都是OK的,问题是在服务器的证书哈希算法,在客户端PC上没有启用。

我在应用程序的配置中添加了一个部分。

<system.diagnostics>
    <trace autoflush="true" />
    <sources>
        <source name="System.Net">
            <listeners>
                <add name="System.Net" />
            </listeners>
        </source>
        <source name="System.Net.Sockets">
            <listeners>
                <add name="System.Net" />
            </listeners>
        </source>
        <source name="System.Net.Cache">
            <listeners>
                <add name="System.Net" />
            </listeners>
        </source>
    </sources>
    <sharedListeners>
        <add
            name="System.Net"
            type="System.Diagnostics.TextWriterTraceListener"
            initializeData="System.Net.trace.log"
        />
    </sharedListeners>
    <switches>
        <add name="System.Net" value="Verbose" />
        <add name="System.Net.Sockets" value="Verbose" />
        <add name="System.Net.Cache" value="Verbose" />
    </switches>
</system.diagnostics>

然后log中的错误让我得到了这个解

我最近也遇到了同样的问题。我的环境运行在。net 4.6.1和VB.NET下。这就是我解决问题的方法:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3
ServicePointManager.ServerCertificateValidationCallback = New RemoteCertificateValidationCallback(AddressOf util.ValidateServerCertificate)

还有util。ValidateServerCertificate函数为:

Public Function ValidateServerCertificate(ByVal sender As Object, ByVal certificate As X509Certificate, ByVal chain As X509Chain, ByVal sslPolicyErrors As SslPolicyErrors) As Boolean
    Return True
End Function

只要这是一个相对“活”的链接,我想我会添加一个新的选项。这种可能性是由于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;