How to ignore SSL/TLS certificate error when making requests to Https Urls from C#

I needed to call an URL and return the response. The URL is in the format “https://xx.xxx.xxx.xxx/api/v1/UserData”.

When I accessed the URL in a browser, I was able to see the response. Because of certificate issue, I would see “Not secure – Your connection to this site is not secure. You should not enter any sensitive information….” warning on the browser.

The final purpose was to access the URL from a program and read the response. Here is the code I started with.

The following are the references needed for the code.

using Newtonsoft.Json;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

Here is the code that uses HttpClient to make a request and reads the response.

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri(UserDataUrl);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new
     MediaTypeWithQualityHeaderValue("application/json"));
    Task response = client.GetStringAsync(UserDataUrl);
    response.Wait();

    if (response.Exception != null)
    {
        return null;
    }

    return JsonConvert.DeserializeObject<UserData>(response.Result);
}

I was not seeing the response and the request was throwing the following exception: {“The request was aborted: Could not create SSL/TLS secure channel.”}.

After some searching, I found that the adding the first two lines of code solved the issue and I was able to get the response.

// trust any certificate
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
ServicePointManager.ServerCertificateValidationCallback +=
    (sender, cert, chain, sslPolicyErrors) => { return true; };
using (var client = new HttpClient())
{
    client.BaseAddress = new Uri(UserDataUrl);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new
      MediaTypeWithQualityHeaderValue("application/json"));
    Task<string> response = client.GetStringAsync(UserDataUrl);
    response.Wait();

    if (response.Exception != null)
    {
         return null;
    }

    return JsonConvert.DeserializeObject<UserData>(response.Result);
}

In my case, the server was using TLS1.2, so I had to add this:

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

It could be some other SecurityProtocolType in your case.

This is for development purposes only. Ignoring or bypassing SSL/TLS errors in production is not advised.

One thought on “How to ignore SSL/TLS certificate error when making requests to Https Urls from C#

Leave a comment