今天写程序的时候调用到一个第三方提供的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服务之前,执行一次即可。代码如下:
{
/// <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;
}
}
这样实现了远程访问https地址 项目部署在win2012 2R上可用