HttpClient Exception 'The response ended prematurely' when actual response length not match Content-Length header

Viewed 373

How I can fix HttpClient Exception when the actual response length is smaller than Content-Length header

The response ended prematurely, with at least 4508 additional bytes expected.

The response ended prematurely, with at least 783 additional bytes expected.

I fixed this exception by reading the response content character by character until the exception happens

var response = await client.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);
var stream = await response.Content.ReadAsStreamAsync();

using var streamReader = new StreamReader(stream);
var content = "";
try
{
    do
    {
        content += (char)streamReader.Read();
    }
    while (!streamReader.EndOfStream);
}
catch (Exception ex)
{
}

but I didn't think this is the right or the optimal solution,

How Can I make HttpClient ignore the Content-Length from the request header?

0 Answers
Related