2

我正在尝试从 https Web 请求创建 XML 文档,但是当站点的证书无效时,我无法使其正常工作。我希望我的应用程序不关心证书,我希望它无所畏惧地生活在边缘!

这是我拥有的初始代码,之前我曾多次使用它从标准 http(非 SSL)请求中获取我想要的内容:

XmlDocument xml = new XmlDocument();
XmlTextReader reader = new XmlTextReader("https://www.example.com");
xml.Load(reader);

由于网站的 SSL 证书无效,我现在收到以下错误:

请求被中止:无法创建 SSL/TLS 安全通道。

现在我已经完成了我的谷歌搜索并尝试了一些有希望的解决方案,但似乎没有任何帮助。

我在这里尝试过的一个看起来不错,但似乎没有用,我直接在上面的代码之前添加了“已接受的答案”代码行,因为它不太清楚应该去哪里。

万一有什么不同,我的代码在类库中,我正在通过控制台应用程序进行测试。我也在使用.Net 4。


这是我最近的尝试(不起作用):

XmlDocument xml = new XmlDocument();

ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback((s, ce, ch, ssl) => true);

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlCommand);
request.Credentials = CredentialCache.DefaultCredentials;

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
    using (Stream receiveStream = response.GetResponseStream())
    {
        XmlTextReader reader = new XmlTextReader(receiveStream);
        xml.Load(reader);
    }
}
4

3 回答 3

2

好的,所以我找到了解决方案。我们选择尝试禁用服务器上的 SSL 进行测试,并注意到它使用的是 SSL 3。在另一次谷歌搜索之后,我发现了一些额外的代码来解决这个问题(对设置很重要SecurityProtocolType):

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback((s, ce, ch, ssl) => true);

XmlDocument xml = new XmlDocument();
XmlTextReader reader = new XmlTextReader(urlCommand);
xml.Load(reader);
于 2012-07-13T12:06:59.010 回答
0

嗯,也许 XmlTextReader 使用不同的方式访问 HTTPS。

尝试使用 , 发出 Web 请求HttpWebRequest并传递response.GetResponseStream()给 XML 文本阅读器(并将ServicePointManager.ServerCertificateValidationCallback覆盖保留在您拥有的地方)

于 2012-07-13T11:23:42.247 回答
0

此错误的原因:

您没有在您的网站上使用有效的客户端证书。

你可以试试下面:

  • 为了快速转身,您可以尝试使用 http://____ * 访问 URL - 不建议这样做,但您可以尝试进行测试。*

  • 因此,您没有使用有效的客户端证书,您可以编写如下内容:

    • 在您请求下载 XML 或发出一些 http 请求的位置添加此行。

    //添加Mock证书验证

    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(OnValidationCallback);

  • 添加以下作为全局方法:

    public static bool OnValidationCallback(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors) { return true; }

于 2021-06-18T13:39:44.447 回答