C# HttpClient: Could not create SSL/TLS secure channel

6.3k Views Asked by At

i want to send a simple request to "https://etebarkala.com".

  1. Tried from .net versions 4.5 to 4.8 with no success
  2. This website opens easily with a browser
  3. There isn't any ssl validation error or warnings

result: The request was aborted: Could not create SSL/TLS secure channel.

var request = new HttpRequestMessage(HttpMethod.Get, new Uri("https://etebarkala.com"));
request.Headers.Add("Accept-Language", "en-US");
request.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:94.0) Gecko/20100101 Firefox/94.0");
request.Headers.Add("Upgrade-Insecure-Requests", "1");
request.Headers.Add("Connection", "keep-alive");


using (HttpClientHandler handler = new HttpClientHandler())
{
    handler.SslProtocols = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12 | SslProtocols.Tls13;//| SslProtocols.Ssl3;//| SslProtocols.Ssl3;
    handler.ServerCertificateCustomValidationCallback = (snder, cert, chain, error) => { return true; };

    ServicePointManager.ServerCertificateValidationCallback = (snder, certificate, chain, errors) => { return true; };

    ServicePointManager.DefaultConnectionLimit = 9999;
    ServicePointManager.Expect100Continue = true;
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13 | SecurityProtocolType.Ssl3 | SecurityProtocolType.Ssl3 | SecurityProtocolType.SystemDefault;

    using (HttpClient client = new HttpClient(handler))
    {
        try
        {
                HttpResponseMessage res = client.SendAsync(request).Result;
                textBox1.Text = res.Content.ReadAsStringAsync().Result;
        }
        catch (Exception e)
        {
                string Result = e.Message;
                textBox1.Text = "Error:" + Result
            + Environment.NewLine + (e.InnerException != null ? e.InnerException.Message : "")
            + Environment.NewLine + (e.InnerException != null && e.InnerException.InnerException != null ? e.InnerException.InnerException.Message : "");

        }
    }
}
2

There are 2 best solutions below

0
On

In my case the permission to access the certificate in local machine store was the problem. I was reading the certificate for the HttpClient from the machine store by its fingerprint and as soon as I called the SendAsync method I got the "The request was aborted: Could not create SSL/TLS secure channel." exception.

Run the certlm.msc in admin mode and right click on the target certificate and select All Tasks -> Manage Private Keys then add the permission to the user that your process is accessing the store under it. If it is IIS it might be NETWORK SERVICE.

1
On

Add this lines of code and you are good to go.

ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;