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

Posted 羽风蓝

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
//}
//}

 

以上是关于Could not establish trust relationship for the SSL/TLS secure channel 问题解决方法的主要内容,如果未能解决你的问题,请参考以下文章

kafka报错异常could not be established解决方案

Kitematic when login show Error:Tunning socket could not be established

报错:Unchecked runtime.lastError:Could not establish connection. Receiving end does not exist.

npm ERR! Error: tunneling socket could not be established的解决问题

Connection could not be established with host smtp.163.com

Google Chrome 插件开发: 无法建立连接, 接收端不存在. Could not establish connection. Receiving end does not exist