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:
'要先Import相關東西
Imports System.Web
Imports System.Net
Imports System.Net.Security
Imports System.Security.Cryptography.X509Certificates

'加入此Function
Private Function ValidateServerCertificate _
                 (ByVal sender As Object, ByVal certificate As X509Certificate, _
                 ByVal chain As X509Chain, ByVal sslPolicyErrors As SslPolicyErrors) As Boolean
    Return True
End Function

'在原本的程式加上底下這行
ServicePointManager.ServerCertificateValidationCallback = New RemoteCertificateValidationCallback(AddressOf ValidateServerCertificate)

'原本的程式
Dim WebRQ As HttpWebRequest
Dim WebRS As HttpWebResponse

WebRQ = CType(WebRequest.Create(url), HttpWebRequest)
WebRQ.Credentials = CredentialCache.DefaultCredentials
WebRQ.CachePolicy = New Cache.HttpRequestCachePolicy(Date.Now)
WebRQ.Method = "POST"
WebRQ.ContentType = "application/x-www-form-urlencoded"
'......

C#:
using System.Web;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

// 加入此Function
// 設定 HTTPS 連線時,不要理會憑證的有效性問題
public static bool ValidateServerCertificate(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) {
    return true;
}

// 在原本的程式加上底下這行
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);

沒有留言:

張貼留言