操作
当向一个https的url上发送请求,报错:未能创建 SSL/TLS 安全通道;
报错前实现代码如下:
/// <summary> /// 判断远程文件是否存在 /// </summary> /// <param name="fileUrl">文件路径</param> /// <returns></returns> public ActionResult FileExists(string fileUrl) { var result = new ResultModel(); HttpWebRequest re = null; HttpWebResponse res = null; try { re = (HttpWebRequest)WebRequest.Create(fileUrl); res = (HttpWebResponse)re.GetResponse(); if (res.ContentLength != 0) { result.Success = true; } } catch (Exception ex) { result.Success = false; result.Message = ex.Message; } finally { if (re != null) { re.Abort();//销毁关闭连接 } if (res != null) { res.Close();//销毁关闭响应 } } return Json(result, JsonRequestBehavior.AllowGet); }
原因:
ssl证书不受信任,验证失败;
解决方案:
1:先加入命名空间
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
2:再重载CheckValidationResult方法,返回true
public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) {
//直接确认,否则打不开
return true;
}
3:然后在HttpWebRequest req =(HttpWebRequest) WebRequest.Create(URL)前面加上如下一行代码
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);//验证服务器证书回调自动验
最终实现代码如下:
/// <summary> /// 判断远程文件是否存在 /// </summary> /// <param name="fileUrl">文件路径</param> /// <returns></returns> public ActionResult FileExists(string fileUrl) { var result = new ResultModel(); HttpWebRequest re = null; HttpWebResponse res = null; try { ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult); re = (HttpWebRequest)WebRequest.Create(fileUrl); res = (HttpWebResponse)re.GetResponse(); if (res.ContentLength != 0) { result.Success = true; } } catch (Exception ex) { result.Success = false; result.Message =ex.Message; } finally { if (re != null) { re.Abort();//销毁关闭连接 } if (res != null) { res.Close();//销毁关闭响应 } } return Json(result, JsonRequestBehavior.AllowGet); }