I’m getting this error from a behavior I don’t understand:
Exception screenshot
I’ve looked online to try to find a solution but nothing worked or applied to my case.
It says that Stream.Length threw an exception but as I found online, people said to check the .CanSeek
method and for each stream open I checked and they all returned true
.
Here’s the proof that it reads the length of the stream:
Debug output ( Sorry for the quality, screenshots were removing the debug output window ).
And this is right before returning the item, in this case a user
, and everything works before it.
Here’s my code for this method:
public async Task<RegistrationResponse> RegisterAsync(RegistrationRequest body)
{
// Create a new instance of the IHttpClientFactory
var httpClient = _httpClientFactory.CreateClient("default");
// Create a MemoryStream to be able to use compression
using (var memoryContentStream = new MemoryStream())
{
await JsonSerializer.SerializeAsync(memoryContentStream, body);
// CAN SEEK returns true
var canSeek = memoryContentStream.CanSeek;
memoryContentStream.Seek(0, SeekOrigin.Begin);
// Use HttpRequestMessage instead of the .PostAsync shortcut but either could be used
using (var httpRequest = new HttpRequestMessage(
HttpMethod.Post,
"/api/Accounts/register"))
{
// Add headers to the call
httpRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpRequest.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
using (var compressedMemoryContentStream = new MemoryStream())
{
// Compress the content
using (var gzipStream = new GZipStream(
compressedMemoryContentStream, CompressionMode.Compress))
{
memoryContentStream.CopyTo(gzipStream);
gzipStream.Flush();
compressedMemoryContentStream.Position = 0;
// CAN SEEK returns true
var canSeek2 = compressedMemoryContentStream.CanSeek;
// Create a stream
using (var streamContent = new StreamContent(compressedMemoryContentStream))
{
// Add headers to the call
streamContent.Headers.ContentType =
new MediaTypeHeaderValue("application/json");
streamContent.Headers.ContentEncoding.Add("gzip");
httpRequest.Content = streamContent;
var response = await httpClient.SendAsync(
httpRequest,
HttpCompletionOption.ResponseHeadersRead);
response.EnsureSuccessStatusCode();
// THIS IS WHERE IT DOESN'T WORK ANYMORE, even thought .Content shows the length of the stream
var stream = await response.Content.ReadAsStreamAsync();
var user = await JsonSerializer.DeserializeAsync<RegistrationResponse>(stream);
return user;
}
}
}
}
}
}