C# WebClient 报错:System.Net.WebException: 基础连接已经关闭: 未能为 SSL/TLS 安全通道建立信任关系

提出问题

使用 WebClienthttps 请求时,在 windows8操作系统报错,如下:

System.Net.WebException: 基础连接已经关闭: 未能为 SSL/TLS 安全通道建立信任关系

分析问题

在windows10中,没有这类问题,猜测应该与操作系统有关

在 windows8 中,发送 https 请求时,由于证书问题导致报错

解决

步骤一

定义下面类

public static class Util
{
    //由于api的特殊性,需要在我们发出请求前,解决未能建立安全通信通道问题,为这次连接设置安全认证
    public static void SetCertificatePolicy()
    {
        ServicePointManager.ServerCertificateValidationCallback
                    += RemoteCertificateValidate;
    }
    private static bool RemoteCertificateValidate(
        object sender, X509Certificate cert,
        X509Chain chain, SslPolicyErrors error)
    {
        // trust any certificate!!!
        System.Console.WriteLine("Warning, trust any certificate");
        return true;
    }
}

步骤二

在创建 WebClient 对象之前调用,如下:

// 先调用
Util.SetCertificatePolicy();
// 然后再创建对象
WebClient client = new WebClient();

参考:
https://blog.csdn.net/quentien/article/details/122326973


原文出处:http://www.malaoshi.top/show_1IX6RDGRIYnk.html