.NET exception “The remote certificate is invalid”


For one project I needed to make a simple tool that fetches file from webserver via HTTPS connection. Sounds easy, right?

There are plenty of ways of doing things, but to keep it simple, lets ignore error handling, timeouts, authorization and other features:

HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create({url_here});
HttpWebResponse response = (HttpWebResponse)httpRequest.GetResponse();
... process response ...

It should work, right?

And yes, it works most of the time. For example, it fetches page from https://google.com/ without any problems.

But for some sites it mysteriously crashes with exception:

Error: System.Net.WebException: The underlying connection was closed: 
Could not establish trust relationship for the SSL/TLS secure channel. ---> 
System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.

Cause of the error

It turns out that sites that are using self-signed, expired and otherwise bad certificates will cause this exception. How nice from .NET devs - they're trying to protect me! Well, no, because I still need to download that information!


I found lots of solutions of the web - and quite a few of them failed. Some of them are .NET 4.5 only, some of them are overly complicated class consisting of 20+ lines. I need something simple, that works everywhere from .NET 2.0 up and is actually readable!

This one works for me: put this line before doing any HTTPS requests:

ServicePointManager.ServerCertificateValidationCallback += delegate {return true;};

It effectively suppresses all certificate validation errors. Problem solved!

Example site for testing your code: https://www.pcwebshop.co.uk/

One thought on “.NET exception “The remote certificate is invalid”

Leave a Reply

  • Be nice to me and everyone else.
  • If you are reporting a problem in my tool, please upload the file which causes the problem.
    I can`t help you without seeing the file.
  • Links in comments are visible only to me. Other visitors cannot see them.

6  ×  1  =