Vishwamohan

Welcome to Vishwa's blog - Technology, Spirituality and More...

Could not establish trust relationship for the SSL/TLS

I got this error when calling a WCF Service over HTTPS. A Similar error can also occurs when you try calling a web service programmatically over SSL (HTTPS) and certificate is either not valid or Certificate is attached to a domain and you are not using the domain name but the machine name or IP address. So, what to do in that case if you don’t care about certificate and would like to accept all certificates. I found that it can be done using one of two ways. 

Main Class – Where you are calling the Web Service, add following Import Statements
Imports System.Security.Cryptography.X509Certificates
Imports System.Net.Security
Imports System.Net
 
Public Class MyWebServiceCall
 
    Public Sub CallServiceUsingFunction()
        'Instanciate the Service here
        'Set all paramaters which you need to pass
        'Before You call the Service
        ServicePointManager.ServerCertificateValidationCallback = AddressOf TrustAllCertificatesCallback
        'Call your service Now.......
    End Sub
 
 
    Public Shared Function TrustAllCertificatesCallback(ByVal sender As Object, ByVal cert As X509Certificate, _
                                                 ByVal chain As X509Chain, ByVal errors As SslPolicyErrors) As Boolean
        Return True
    End Function
    Public Sub CallServiceUsingClass()
        'Instanciate the Service here
        'Set all paramaters which you need to pass
        'Before You call the Service
        Dim CertOverride As New CertificateOverride
        ServicePointManager.ServerCertificateValidationCallback = AddressOf CertOverride.RemoteCertificateValidationCallback
        'Call your service Now.......
    End Sub
End Class
 CertificateOverride Class - An Alternate Option
Public Class CertificateOverride
    Public Function RemoteCertificateValidationCallback(ByVal sender As Object, ByVal certificate As X509Certificate, ByVal chain As X509Chain, _
            ByVal sslPolicyErrors As SslPolicyErrors) As Boolean
        Return True
    End Function
End Class

 

Comments (4) -

  • Naveen

    6/28/2008 8:37:44 PM | Reply

    Hey Vishwa..Thanks..this post was very helpful..

  • mbarriosc

    11/17/2008 3:53:49 AM | Reply

    Hi!! thank you so much. It helped me!!!

  • Amit

    3/30/2009 1:25:14 AM | Reply

    Hi,

    Could you please tell me if I have to resolve the same issue but without programming which means by changing anything in web.config then what should I be doing?

    Any help on this will be greatly appreciated.

    Thanks,
    Amit.

  • Neelima

    6/29/2009 12:55:17 AM | Reply

    Thanks Vishwa!
    Your solution saved me a lot of headache.

    -Neelima

Loading