Error "the underlying connection was closed" in HttpClient C rest request#
I am doing an integration in rest with C# used HttpClient, most of the time the data was sent successfully, but I went to investigate why some were returning with error, I found that what they had in common, was that the JSON sent was a little bigger than the others (had more data), I found in some forums that this is a recurring BUG of the .NET and tried some solutions pointed, request, and also change the version of HTTP to 1.0, both without success.
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 excerpt 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;
```
0
Author: David Helfer, 2020-01-31