Search code examples
c#sslpostasync

PostMan Token works but source code has error: The request was aborted: Could not create SSL/TLS secure channel during trace


I have a code for getting token. It works in live server. But when I am tracing the code in my system I get this error:

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

When I try to get token by Postman on my system, no error occurs. So why does the error occur? It is driving me crazy so I would appreciate any help.

Here is my code:

var clientKey = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("client_id", XXXX),
                new KeyValuePair<string, string>("client_secret", YYY),
                new KeyValuePair<string, string>("grant_type", "client_credentials")
            });

        clientKey.Headers.ContentType.Parameters.Add(new NameValueHeaderValue("client_id", XXXX));
        clientKey.Headers.ContentType.Parameters.Add(new NameValueHeaderValue("client_secret", YYY));
        clientKey.Headers.ContentType.Parameters.Add(new NameValueHeaderValue("grant_type", "client_credentials"));
        
        var url = TokenUrl;
        var client = new HttpClient();

        client.DefaultRequestHeaders.Add("Cookie", "cookiesession1=xxxxxxxxxxxxxx");

        var httpResponse = client.PostAsync(url, clientKey).Result;

Solution

  • Finally I found a solution by adding these codes to my source. Since in live server there is no need to this code, I put this on a block which only works if it is test server:

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