System.Net.WebException: 基礎連線已經關閉: 未能為 SSL/TLS 安全通道建立信任關係。 ---> System.Security.Authentication.AuthenticationException: 根據驗證過程,遠端證書無效。
今天寫程式的時候呼叫到一個第三方提供的https地址,訪問此地址去獲取加密的json格式資料,出現BUG
c#報錯 : System.Net.WebException: 基礎連線已經關閉: 未能為 SSL/TLS 安全通道建立信任關係。 ---> System.Security.Authentication.AuthenticationException: 根據驗證過程,遠端證書無效。
引用:
private string callbackRefund(string url, string data)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "POST";
byte[] bytes = UTF8Encoding.UTF8.GetBytes(data);
request.ContentLength = bytes.Length;
request.ContentType= "application/json";
long x_ts = GetCurrentTimeUnix();
request.Headers.Add("x-ts", x_ts.ToString());
request.Headers.Add("x-hospitalId", "40617");
request.Headers.Add("x-sig", "kinyer_debug_sign");
using (Stream requestStream = request.GetRequestStream())
{
foreach (byte b in bytes)
{
requestStream.WriteByte(b);
}
}
using (WebResponse response = request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
byte[] responseContent;
using (MemoryStream ms = new MemoryStream())
{
responseStream.CopyTo(ms);
responseContent = ms.ToArray();
}
return UTF8Encoding.UTF8.GetString(responseContent);
}
}
}
解決方法:
步驟一:定義一個類,來對遠端X.509證書的驗證,進行處理,返回為true.我們要自己定義一個類,然後在客戶單呼叫WCF服務之前,執行一次即可。程式碼如下:
public static class Util
{
/// <summary>
/// Sets the cert policy.
/// </summary>
public static void SetCertificatePolicy()
{
ServicePointManager.ServerCertificateValidationCallback
+= RemoteCertificateValidate;
}
/// <summary>
/// Remotes the certificate validate.
/// </summary>
private static bool RemoteCertificateValidate(
object sender, X509Certificate cert,
X509Chain chain, SslPolicyErrors error)
{
// trust any certificate!!!
System.Console.WriteLine("Warning, trust any certificate");
return true;
}
} 步驟二: 你要在HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);呼叫操作點前先呼叫這個方法: Util.SetCertificatePolicy();
這樣實現了遠端訪問https地址 專案部署在win2012 2R上可用