The request was aborted: Could not create SSL/TLS secure channel. when calling PostAsJsonAsync

Viewed 863

I am sending a request to third party website by PostAsJsonAsync as below:

var nbParamsJson = Newtonsoft.Json.JsonConvert.SerializeObject(nbParams);
  var httpContent = new StringContent(nbParamsJson);
  try
  {
    var response = await client.PostAsJsonAsync(siteUrl, httpContent);

  }
  catch (Exception exp)
  {

  }

which throws an exception: [The request was aborted: Could not create SSL/TLS secure channel.] I know my website in test environment does not have a SSL certificate and probably is happening because the third-party website has SSL certificate. I want to know is there any way to create SSL channel without moving to SSL.

2 Answers

I just added

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

before PostAsJsonAsync and it solved my issue.

I'm not sure of your async, but here is an adaptation from working code to send JSON data to an SSL website that you should be able to adapt to your specific case:

        var baseurl = "https://example.com/api/upload/123";
        var rqst = (HttpWebRequest)WebRequest.Create(baseurl);
        rqst.Method = "PUT";
        rqst.Accept = "application/json";
        var authInfo = "authtoken";
        rqst.Headers["Authorization"] = "Token  " + authInfo;
        rqst.UserAgent = "curl/7.37.0";
        rqst.ContentType = "application/json; charset=utf-8";

        using (var streamWriter = new StreamWriter(rqst.GetRequestStream()))
        {
            streamWriter.Write(GetJsonData());
        }

        try
        {
            var resp = rqst.GetResponse();
            using (var sr = new StreamReader(resp.GetResponseStream() ?? throw new InvalidOperationException()))
            {
                var txt = sr.ReadToEnd();
                textBox1.Text = txt;
            }
        }
        catch (Exception ex)
        {
            textBox1.Text = ex.Message;
        }
Related