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


当前回答

对我来说,问题是我试图将IIS作为web服务部署在服务器上,我在服务器上安装了证书,但运行IIS的用户对证书没有正确的权限。

如何给ASP。NET访问证书存储中的证书中的私钥?

其他回答

这是原始答案所没有的。我又加了些代码让它防弹。

ServicePointManager.Expect100Continue = true;
        ServicePointManager.DefaultConnectionLimit = 9999;
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;

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

在我的例子中,运行应用程序的服务帐户没有访问私钥的权限。一旦我给予了这个许可,错误就消失了

mmc 证书 扩展到个人 选择证书 右击 所有任务 管理私钥 添加业务帐户用户

您遇到的问题是aspNet用户没有访问证书的权限。您必须使用winhttpcertcfg.exe提供访问权限

关于如何设置的示例如下: http://support.microsoft.com/kb/901183

详细信息请参见步骤2

编辑:在最新版本的IIS中,此功能内置于证书管理器工具中-可以通过右键单击证书并使用管理私钥的选项来访问。更多详情请访问:https://serverfault.com/questions/131046/how-to-grant-iis-7-5-access-to-a-certificate-in-certificate-store/132791#132791

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

在我的情况下,两者都是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中的错误让我得到了这个解