Could not establish trust relationship for the SSL/TLS secure channel

Let’s say we want to use RestSharp to call an API method in an Azure-hosted environment over HTTPS.

var client = new RestClient("https://randomqaenvironment.cloudapp.net");
var request = new RestRequest("resource/{id}", Method.POST);
request.AddUrlSegment("id", 123);
client.Execute<Person>(request);

This method will work fine as long as you are using a trusted certificate in your deployment. However, most QA/Dev environments typically use a self-hosted certificate to save on cost, which will result in the following error:

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

The most straightforward way to get around this issue is to create your own custom validation of server certificates using the ServerCertificateValidationCallback property. Add this code to the top of any method that calls the target API and/or the Run() method in the project’s WebRole.cs file if you are using Azure.

ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;

The code above will trust any security certificate handed back from the server you are interacting with so be sure you trust it. In most cases this won’t be an issue since you control the server on the other end.

Creative Commons License

What do you think?