操做安全
當向一個https的url上發送請求,報錯:未能建立 SSL/TLS 安全通道;服務器
報錯前實現代碼以下:url
/// <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); }
緣由:spa
ssl證書不受信任,驗證失敗;code
解決方案:blog
1:先加入命名空間ssl
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;string
2:再重載CheckValidationResult方法,返回trueit
public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) {io
//直接確認,不然打不開
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); }