2

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?

  • Can you instead try something like: `using (var reader = new StreamReader(response.GetResponseStream(), ASCIIEncoding.ASCII)) { content = reader.ReadToEnd(); }` (borrowed from https://stackoverflow.com/a/3273252/6621862) – Luke Jan 06 '22 at 20:00
  • It might seem a silly question but why is `Content-Length` bigger than the content body? – Peter Csala Jan 07 '22 at 08:49
  • @Luke yes i tried this but its same exception happens without any output – Ahmed Fayez Jan 07 '22 at 21:42
  • @Peter Csala, this issue from API provider i contact them, but i tring to discover a solution or workaround for this if i blocked in this same case later, specially the request work in chrome and postman without errors – Ahmed Fayez Jan 07 '22 at 21:50

0 Answers0