Code Repo    |     RSS
MD's Technical Sharing



Thursday, October 16, 2008

TrustFailure exception during HTTPWebRequest via HTTPS connection

If an HTTPWebRequest is made via a secure connection (HTTPS) and the certificate is not trusted, a WebException with Exception.Status = TrustFailure will be thrown. To bypass this, we need to explicitly declare a custom certificate policy in a separate class:


Imports System.Net
Imports System.Security.Cryptography.X509Certificates

Public Class TrustAllCertificatePolicy
Implements System.Net.ICertificatePolicy

'default empty constructor
Public Sub New()
End Sub

Public Function CheckValidationResult(ByVal sp As ServicePoint, ByVal cert As X509Certificate, ByVal req As WebRequest, ByVal problem As Integer) As Boolean Implements ICertificatePolicy.CheckValidationResult
'return true to accept all certificates. Otherwise examine 'cert' and return either TRUE or FALSE according to its properties
Return True
End Function

End Class


Before the call to HTTPWebRequest, explicitly state the custom policy:

System.Net.ServicePointManager.CertificatePolicy = New TrustAllCertificatePolicy()


Reference: http://www.pcreview.co.uk/forums/thread-1226590.php

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.