后台搭建在局域网机器上,如https://192.168.1.2/api/,客户端使用HttpWebRequest发出请求时,提示 “基础连接已经关闭: 未能为SSL/TLS 安全通道建立信任关系 错误的解决办法”,很明显这是SSL证书问题,如果不想自己签发证书,可以用以下方法解决。
在请求的类里面增加以下函数:
1 2 3 4 5 6 7 8 9 10 11 12 |
/// <summary> /// 解决Error"基础连接已经关闭: 未能为SSL/TLS 安全通道建立信任关系。" /// </summary> /// <param name="sender"></param> /// <param name="certificate"></param> /// <param name="chain"></param> /// <param name="sslPolicyErrors"></param> /// <returns></returns> private static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; } |
然后在请求之前加上这一句,设置证书回调函数:
1 |
System.Net.ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate; |
比如这样:
1 2 3 4 5 |
System.Net.ServicePointManager.DefaultConnectionLimit = 100; //这个值默认是2 System.Net.ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate; HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(new Uri(uriString)); httpWebRequest.Method = "POST"; ............ |
OK了,记得正式发布前将此修改注释掉,否则影响程序安全。