2011-05-25

WebRequest物件如何忽略憑證問題

如果目的端網頁是https,而憑證主機名稱和實際名稱不一樣的話,在IE上會出現這種畫面


要點下”是”才能繼續瀏覽


但是如果利用WebRequest元件的話,就會卡在這裡,變成無法取得網頁內容,空白一片

要解決這種問題,可以參考 http://blog.miniasp.com/post/2007/11/01/The-remote-certificate-is-invalid-according-to-the-validation-procedure.aspx

裡面有說明如何解決這問題

底下也可參考程式碼:

VB:
  1. '要先Import相關東西
  2. Imports System.Web
  3. Imports System.Net
  4. Imports System.Net.Security
  5. Imports System.Security.Cryptography.X509Certificates
  6. '加入此Function
  7. Private Function ValidateServerCertificate _
  8.                  (ByVal sender As Object, ByVal certificate As X509Certificate, _
  9.                  ByVal chain As X509Chain, ByVal sslPolicyErrors As SslPolicyErrors) As Boolean
  10.     Return True
  11. End Function
  12. '在原本的程式加上底下這行
  13. ServicePointManager.ServerCertificateValidationCallback = New RemoteCertificateValidationCallback(AddressOf ValidateServerCertificate)
  14. '原本的程式
  15. Dim WebRQ As HttpWebRequest
  16. Dim WebRS As HttpWebResponse
  17. WebRQ = CType(WebRequest.Create(url), HttpWebRequest)
  18. WebRQ.Credentials = CredentialCache.DefaultCredentials
  19. WebRQ.CachePolicy = New Cache.HttpRequestCachePolicy(Date.Now)
  20. WebRQ.Method = "POST"
  21. WebRQ.ContentType = "application/x-www-form-urlencoded"
  22. '......

C#:
  1. using System.Web;
  2. using System.Net;
  3. using System.Net.Security;
  4. using System.Security.Cryptography.X509Certificates;
  5. // 加入此Function
  6. // 設定 HTTPS 連線時,不要理會憑證的有效性問題
  7. public static bool ValidateServerCertificate(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) {
  8.     return true;
  9. }
  10. // 在原本的程式加上底下這行
  11. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);

沒有留言:

張貼留言