天天看點

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