1

I am trying to send off a post request using .net framework to an external API and it keep failing with a bunch of errors and throwing a 500 that I cant seem to understand whats going on.

The request requires two headers content-type and authorization

 using (var client = new HttpClient())
            {
                try
                {
                    var url = new Uri("https://api.intelepeer.com/_rest/v4/app/sms/send");
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", "********************************");

                    var stringContent = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json");
                    var response = client.PostAsync(url,  stringContent).Result;
                    if (response.IsSuccessStatusCode)
                    {
                        success = 1;
                    }
                    else
                    {
                        fail = 1;
                        throw new HttpUnhandledException("Call to service failed");
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("Call to service failed", ex);
                }
            }

Data being sent:

[
  {to: "+11234567890, from: "+13245345533, text: "asdfh hasjdfhas"}
]

Exception Messages:

ExceptionMessage: "Call to service failed"
ExceptionType: "System.Exception"
InnerException: {Message: "An error has occurred.", ExceptionMessage: "One or more errors occurred.",…}
ExceptionMessage: "One or more errors occurred."
ExceptionType: "System.AggregateException"
InnerException: {Message: "An error has occurred.", ExceptionMessage: "An error occurred while sending the request.",…}
ExceptionMessage: "An error occurred while sending the request."
ExceptionType: "System.Net.Http.HttpRequestException"
InnerException: {Message: "An error has occurred.",…}
ExceptionMessage: "The underlying connection was closed: An unexpected error occurred on a send."
ExceptionType: "System.Net.WebException"
InnerException: {Message: "An error has occurred.",…}
ExceptionMessage: "Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host."
ExceptionType: "System.IO.IOException"
InnerException: {Message: "An error has occurred.",…}
ExceptionMessage: "An existing connection was forcibly closed by the remote host"
ExceptionType: "System.Net.Sockets.SocketException"
Message: "An error has occurred."
StackTrace: "   at System.Net.Sockets.Socket.EndReceive(IAsyncResult asyncResult)
↵   at System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)"
Message: "An error has occurred."
StackTrace: "   at System.Net.TlsStream.EndWrite(IAsyncResult asyncResult)
↵   at System.Net.ConnectStream.WriteHeadersCallback(IAsyncResult ar)"
Message: "An error has occurred."
StackTrace: "   at System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult, TransportContext& context)
↵   at System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar)"
Message: "An error has occurred."
StackTrace: null
Message: "An error has occurred."
StackTrace: "   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
↵   at BabelFish.Business.SendManager.Send(DtoSendRequest request) in C:\$Default\Babel Fish\Main\Source\BabelFish\BabelFish.Business\SendManager.cs:line 52"
Message: "An error has occurred."
Charles L.
  • 1,844
  • 2
  • 34
  • 56
  • Google your exceptions. You'll get a cleaner picture of why it might be failing. Look at [this](https://stackoverflow.com/questions/2582036/an-existing-connection-was-forcibly-closed-by-the-remote-host) for example. – Adrian Dec 05 '19 at 16:54
  • this might not be the case, but the data you send is missing 2 quotations, for `to` and `from` – Ashkan Mobayen Khiabani Dec 05 '19 at 16:54
  • What version of .net are you using? framework or core? – Joe Phillips Dec 05 '19 at 16:55
  • @JoePhillips Framework – Charles L. Dec 05 '19 at 16:56
  • 2
    You should also resist using `var response = client.PostAsync(url, stringContent).Result;` because the .Result is going to cause you massive headaches. If you can, try to use async/await instead. If not, at least use `GetAwaiter().GetResult()` – Joe Phillips Dec 05 '19 at 16:56
  • Check and make sure URI is valid – Jawad Dec 05 '19 at 16:56
  • @Jawad URI is valid, i can successfully hit the API using SOAP UI – Charles L. Dec 05 '19 at 16:57
  • What is the specific response code (`response.StatusCode`)? – Ben Osborne Dec 05 '19 at 17:03
  • @BenOsborne Status Code: 500 Internal Server Error – Charles L. Dec 05 '19 at 17:03
  • 1
    While it may not be the same thing, the twitter api feed reported back a similar error which required setting the correct security protocol (I can see you're using an https endpoint). [See this question about tls and twitter api feed](https://stackoverflow.com/questions/57271345/twitter-api-responds-with-an-existing-connection-was-forcibly-closed-by-the-rem) – Phil Cooper Dec 05 '19 at 17:07
  • The message indicates that the remote server is closing the connection before you've read the results. I don't see a reason why this would consistently happen due to your code, so they may just be closing the connection early. Can you see what happens using postman instead? – Joe Phillips Dec 05 '19 at 17:19
  • upvote for this very likely being a TLS version issue as mentioned by @PhilCooper – Tom W Dec 05 '19 at 17:30

1 Answers1

2

This is likely a TLS issue. If your application is running less than .Net Framework 4.6, TLS 1.2 is not automatically supported. Try adding this to your application:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

or if you need to support other versions:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
Mideus
  • 124
  • 1
  • 8