天天看点

C#调用webapi HTTPS报错:基础连接已经关闭: 未能为 SSL/TLS 安全通道建立信任关系--安全证书问题

1、首先加入命名空间:

using System.Net.Security;

using System.Security.Authentication;

using System.Security.Cryptography.X509Certificates;

SSL网站,连接时需要提供证书,对于非必须提供客户端证书的情况,只要返回一个安全确认即可。我的是.NET FrameWork4.0

2、加入以下代码:

public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
    {
        //直接确认,否则打不开
        return true;
    }
           

3、接收证书进行身份验证ssl,在调用api接口前调用此方法:

ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);

以下是完整案例:

public string HttpPost(string url, string body)
    {
        Encoding encoding = Encoding.UTF8;
        string jsonText = string.Empty;
        string dataText1 = string.Empty;
        if (string.IsNullOrEmpty(url.Trim()))
        {
            return "";
        }
        //接收证书进行身份验证
        ServicePointManager.ServerCertificateValidationCallback =
            new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
        //ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "POST";
        request.Accept = "text/plain, */*; q=0.01";
        request.ContentType = "application/json;charset=utf-8";
        byte[] buffer = encoding.GetBytes(body);
        request.ContentLength = buffer.Length;
        request.GetRequestStream().Write(buffer, 0, buffer.Length);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
        {
            jsonText = reader.ReadToEnd();
            dataText1 = Regex.Replace(jsonText, @"\\", "");
        }
        return dataText1;
    }