Could not establish trust relationship for the SSL/TLS secure channel 问题解决方法

最近在写一个跟第三方对接的数据同步服务,在本地都没有问题,今天放到生产环境测试报错:

System.Net.WebException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

对方用的是https,看错误是证书问题,查了一些资料,貌似说这个问题的比较少,所以在此总结一下,以防以后用到。

public string GetResponseData(string jsonData, string url)
{
byte[] bytes = Encoding.UTF8.GetBytes(jsonData);

//1.1 在2.0下ServicePointManager.CertificatePolicy已经过时 
//ServicePointManager.CertificatePolicy = new AcceptAllCertificatePolicy();

//2.0 https
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentLength = bytes.Length;

request.ContentType = "application/json";
Stream reqstream = request.GetRequestStream();
reqstream.Write(bytes, 0, bytes.Length);
//设置连接超时时间
request.Timeout = 60000;

request.Headers.Set("Pragma", "no-cache");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream streamReceive = response.GetResponseStream();
Encoding encoding = Encoding.UTF8;

StreamReader streamReader = new StreamReader(streamReceive, encoding);
string strResult = streamReader.ReadToEnd();
streamReceive.Dispose();
streamReader.Dispose();

return strResult;
}
return "";
}

//2.0 https

public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true;
}

// 1.1
//internal class AcceptAllCertificatePolicy : ICertificatePolicy
//{
//public AcceptAllCertificatePolicy()
//{
//}

//public bool CheckValidationResult(ServicePoint sPoint, System.Security.Cryptography.X509Certificates.X509Certificate cert, WebRequest wRequest, int certProb)
//{
//return true;
//}
//}

上一篇:数据库索引<二> 补充前篇


下一篇:TurnipBit口袋编程计算机:和孩子一起DIY许愿的流星