"The underlying connection was closed" error in REST Httpclient C#

Asked

Viewed 339 times

0

I’m doing a REST integration with C# used Httpclient, most of the time the data was sent successfully, but I went to investigate why some of these were returning with error, found that what they had in common, was that the sent JSON was a little bigger than the others (had more data), I discovered in some forums that this is a recurring BUG from . NET and I tried some solutions pointed out, for example set the Keep-Alive in the header of the request, and also change the version of HTTP to 1.0, both unsuccessfully.

The error returned is this:

System.Net.Http.HttpRequestException: Ocorreu um erro ao enviar a solicitação. ---> System.Net.WebException: A conexão subjacente estava fechada: Erro inesperado em um recebimento. ---> System.IO.IOException: Não é possível ler os dados da conexão de transporte: Foi forçado o cancelamento de uma conexão existente pelo host remoto. ---> System.Net.Sockets.SocketException: Foi forçado o cancelamento de uma conexão existente pelo host remoto
   em System.Net.Sockets.Socket.EndReceive(IAsyncResult asyncResult)
   em System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)
   --- Fim do rastreamento de pilha de exceções internas ---
   em System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)
   em System.Net.PooledStream.EndRead(IAsyncResult asyncResult)
   em System.Net.Connection.ReadCallback(IAsyncResult asyncResult)
   --- Fim do rastreamento de pilha de exceções internas ---
   em System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
   em System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
   --- Fim do rastreamento de pilha de exceções internas ---
   em System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   em System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   em System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()

Below snippet of the code where I make the request:

using (var client = new HttpClient())
        {
        client.BaseAddress = new Uri(baseUrl);
        client.DefaultRequestHeaders.Clear();
        client.DefaultRequestHeaders.Accept.Add(new 
        MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Host = "192.168.77.23:4002";
        client.DefaultRequestHeaders.Add("Action", metodo);

        //Adicionado aqui para ver se persiste conexão - segundo solução apontada em alguns 
        fóruns
        client.DefaultRequestHeaders.Add("Connection", "keep-alive");
        client.DefaultRequestHeaders.Add("Keep-Alive", "5000");      

        var content = new StringContent(req, Encoding.UTF8, "application/json");                                                     

        try
        {                   

         HttpResponseMessage res = new HttpResponseMessage();

       // Trocada versão do HTTP segundo solução apontada em alguns fóruns
       res.Version = System.Net.HttpVersion.Version10;

       res = await client.PostAsync(baseUrl + req, content);                                                                  

       res.EnsureSuccessStatusCode();
       string resContent = res.Content.ReadAsStringAsync().Result;
       dynamic resultado = JsonConvert.DeserializeObject(resContent);       

       string erro = resultado.Header.Error;

    ```
  • Apis for security deny requests that have very large json. It is very likely that the 192.168.77.23 host is blocking your request. Then you won’t solve the problem in the request, but in the API you receive. If the API is from a third party, contact them. If the API is yours, you can set the default size limit and increase it, as much as it will open your API to having other security and performance issues.

  • Interestingly, the API is third party, when I send the JSON of my request to them, they manage to make the inclusion smoothly, including send me the return of the api successfully, searching found other cases saying it is a BUG of . NET so I went that way, if it was something on their server they wouldn’t have trouble either?

  • Could have, I think the way to go now would be to contact them and check if they have a log to see what the real problem is.

  • The size and/or response time also increases depending on the size of the sent object?

  • no, it is the same time of a request that comes back successfully, I think the problem is that the request starts to take a little longer and something cuts the connection abruptly, but when they make the request in the language and environment that work right, I will try to do with POSTMAN to test..

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.