Error: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

Certificates. It’s always a pain.

So when you’re attempting to access a remote webservice, regardless if it’s SOAP or REST, and your browser already gives you the headsup:

Example_Invalid_SSL_Certificate

… you know the pain is coming to a theater near you very soon. Invalid SSL certificates will hurt you – the developer.

Take for example a simple C# WebRequest in consideration. By default, the ServicePointManager plays it safe and hooks into all your requests. If the SSL is invalid, your WebRequest will fail with the following exception:

The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

Fixing it the proper way is easy: make sure you’re talking to a valid SSL certificate. But, when you’re reading this that is probably not an option. In this case there is a workaround, albeit a bit risky one. Simply tell the (static) ServicePointManager to skip all checks on remote certificates for you application, as so:

// tell the ServicePointManager to skip all SSL checks
// ... at your own risk
ServicePointManager.ServerCertificateValidationCallback = new
RemoteCertificateValidationCallback
(
   delegate { return true; }
);

And do note the “at your own risk” part. Although you probably realise what this does and what kind of security implications this . By overriding the default checks with the snippet above you’re making sure

It also raises the question: why would anyone allow you to do this? Are there any valid reasons on why you would like to skip this? Sure. Give it a bit of imagination and think for example a unit, or integration, test with this purpose where you deliberately want to test what happens on, for example, an internal self-signed SSL certificate. In the end, the option is available. And it smells. But from a pragmatic point of view, this continues the show.