Bypass SSL certificate validation

A workaround quick solution when your SSL certificate expires

  • Share

If you try to make a WebRequest to a server over https, you might run into the following exception.

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://someurl.com/service/");
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
    
 
"The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel." inner Exception.Message is: "The remote certificate is invalid according to the validation procedure."

This exception is caused by invalid or expired SSL certificate. As soon as SSL certificate is expired, server will start to use self-signed certificate which fails validation.

Even if you try to access the URL to which you are trying to create a request in a browser you will get the following screen

Sslsecuritycertificateerror 1

Web Service Error In Chrome Small

How ever you can resolve this issue by declaring custom validation method.

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
    

In this example, validation method is overridden by custom method which always returns true value.

So before making a request, declare this callback method

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };  
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://someurl.com/service/");
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
    

This way, validation will always pass as your custom method always returns true value.

References

  • Share

Disclaimer

Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.

Comments for this article

comments powered by Disqus