HttpClient post method throws "System.IO.IOException: Unable to read data from the transport connection: The connection was closed." exception

Viewed 38

I have a problem with calling a external service with post method via HttpClient. When I call the external service to get data the HttpClient throws following exception:

System.IO.IOException: Unable to read data from the transport connection: The connection was closed.

This error only occurs when the response message contains larger amount of data. When I prepare requests that return a JSON with an empty array in it the post call proceeds correctly. But when I try a request, which result should be populated with larger amount of data I get this exception. I have searched for the solution of this problem on Internet, and I found a solution that implies, that I should set properly System.Net.ServicePointManager.SecurityProtocol correctly with following line:

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

But this didn’t help in my case. I noticed that when I send my request through Postman, the service responds correctly, no matter how big the response payload will be. On Postman I checked the headers in requests and after a while I noticed, that when I do not include Accept-Encoding: gzip header in my request, Postman will have too problems with returning response.

I tried to use this in my code and force HttpClient to use Accept-Encoding header but with no success. Below is my current HttpClient configuration:

using (HttpClient client = new HttpClient(new HttpClientHandler
{
    AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
}))
{
    client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
    client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("deflate"));

    client.BaseAddress = _uri;
    client.DefaultRequestHeaders.Accept.Clear();
    client.Timeout = TimeSpan.FromSeconds(_timeout);
    client.DefaultRequestHeaders.Add("ApiKey", _apiKey);
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    client.DefaultRequestHeaders.ConnectionClose = false;
    System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
    
    HttpResponseMessage result = await client.PostAsync(uri, content)

    if (result.IsSuccessStatusCode)
    {
        string resultString = await result.Content.ReadAsStringAsync();
        model = JsonConvert.DeserializeObject<T>(resultString);
    }
    else
    {
        await ResponseErrorThrow(result);
    }

    return model;
}

I have no more ideas at the moment. Can you help me with this problem?

0 Answers
Related