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

System.Net.WebException: 基础连接已经关闭: 未能为 SSL/TLS 安全通道建立信任关系。 —> System.Security.Authentication.AuthenticationException: 根据验证过程,远程证书无效。

解决方法:

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;
            }
        }

写一个utils类,当你在

class HttpUitls
    {
        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;
            }
        }
        public static string Get(string Url)
        {
            
            Util.SetCertificatePolicy();

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Proxy = null;
            request.KeepAlive = false;
            request.Method = "GET";
            request.ContentType = "application/json; charset=UTF-8";
            request.AutomaticDecompression = DecompressionMethods.GZip;
            //get请求,返回json文件
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
            string retString = myStreamReader.ReadToEnd();

            myStreamReader.Close();
            myResponseStream.Close();

            if (response != null)
            {
                response.Close();
            }
            if (request != null)
            {
                request.Abort();
            }
            return retString;
        }

    }
}

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);

上面这个代码前添加这个方法
Util.SetCertificatePolicy();
为本次连接设置证书。

你可能感兴趣的:(ssl,安全,.net)