程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> .NET實例教程 >> 1.1和2.0下進行https請求的不同實現

1.1和2.0下進行https請求的不同實現

編輯:.NET實例教程

     今天做項目中進行https請求時遇到這樣的調試錯誤,內部錯誤:未能為 SSL/TLS 安全通道建立信任關系。錯誤頁面:根據驗證過程,遠程證書無效。經過分析,在浏覽器中打開要進行一個安全確認。就是這個對話框引起的問題。在網上搜了一下一般的解決辦法,但是搜的內容比較少,現在在這裡總結一下。
  
  using System;
  using System.Data;
  using System.Configuration;
  using System.Web;
  using System.Web.Security;
  using System.Web.UI;
  using System.Web.UI.WebControls;
  using System.Web.UI.WebControls.WebParts;
  using System.Web.UI.HtmlControls;
  using System.Net;
  using System.IO;
  using System.Text;
  using System.Net.Security;
  using System.Security.Authentication;
  using System.Security.Cryptography.X509Certificates;
  
  public partial class _Default : System.Web.UI.Page
  {
   protected void Page_Load(object sender, EventArgs e)
   {
   //for 1.1 在2.0下ServicePointManager.CertificatePolicy已經過時
   //ServicePointManager.CertificatePolicy = new AcceptAllCertificatePolicy();
   //for 2.0
   //ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
   HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://someurl");
   request.Method = "GET";
   HttpWebResponse response = (HttpWebResponse)request.GetResponse();
   Stream receiveStream = response.GetResponseStream();
   StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
   Page.Response.Write(readStream.ReadToEnd());
   response.Close();
   readStream.Close();
   }
   //for 2.0
   public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
   { // Always accept
   return true;
   }
   //for 1.1
   internal class AcceptAllCertificatePolicy : ICertificatePolicy
   {
   public AcceptAllCertificatePolicy()
   {
   }
  
   public bool CheckValidationResult(ServicePoint sPoint, System.Security.Cryptography.X509Certificates.X509Certificate cert, WebRequest wRequest, int certProb)
   {
   // Always accept
   return true;
   }
   }
  }
  
  http://www.cnblogs.com/david8k/archive/2006/11/06/551911.Html
  

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved