System.Net.Http.HttpRequestException: ‘An error occurred while sending the request.’

Sudenly I received a strange error in a production website while trying to do a simple http request that was working fine the previous day. The error that was thrown was the following:

   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at CL.Helper.Api.MailChimpController.<AddUserToList>d__5.MoveNext() 

This line was trying to make a call to an API endpoint at MailChimp that added an email to a list. Testing the code locally and using unit testing worked perfectly and without any issue.

After debuging the error locally I found out that the details where hiding in the inner exception that were not exposed in the logs and the issue had to do with the server not being able to create a secure channel with the client. The message was: The request was aborted: Could not create SSL/TLS secure channel.

   at System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult, TransportContext& context)
   at System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar)

So investigating a bit I realised that most likely MailChimp stopped supporting older protocols and now only allowed TLS12. Good news there was a simple fix to that:

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

Simply adding the two lines above before the request fixed the issue.

Leave a Reply

Your email address will not be published. Required fields are marked *