/// <summary> Deserialize Json streams </summary>
/// <param name="response"> The message we got to deserialize </param>
/// <param name="cancellationToken"> Cancellation settings depending on request </param>
/// <typeparam name="TResult"> Generic parameter </typeparam>
/// <returns> The <see cref="Task" />. we return the task </returns>
private static async Task<TResult> DeserializeAsync<TResult>(
HttpResponseMessage response,
CancellationToken cancellationToken)
{
await using var contentStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
#if DEBUG
using var reader = new StreamReader(contentStream);
var text = await reader.ReadToEndAsync().ConfigureAwait(false);
Debug.WriteLine("RECEIVED: " + text);
#endif
return await JsonSerializer.DeserializeAsync<TResult>(
contentStream,
_serializerOptions,
cancellationToken).ConfigureAwait(false);
}
Pretty simple code, it deserialises http response. But it crashes on the return. Both sets works on their own, return await deserialises async properly if I use it in release mode, but in debug mode the return wait fails because I believe the reader alters the stream. How do I fix this?
Should I make a copy of the stream and store that?
I've tried resetting the contentStream back to 0 but that just crashed the program instead.
Edit 3: Attempt 3:At @Magnus result Final fully working Implementation: Credit to User @Magnus
private static async Task<TResult> DeserializeAsync<TResult>(
HttpResponseMessage response,
CancellationToken cancellationToken)
{
await using var contentStream = await GetStream(response).ConfigureAwait(false);
#if DEBUG
contentStream.Position = 0;
var reader = new StreamReader(contentStream);
var text = await reader.ReadToEndAsync().ConfigureAwait(false);
contentStream.Position = 0;
Debug.WriteLine("RECEIVED: " + text);
#endif
return await JsonSerializer.DeserializeAsync<TResult>(
contentStream,
_serializerOptions,
cancellationToken).ConfigureAwait(false);
}
private static async Task<Stream> GetStream(HttpResponseMessage response)
{
var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
#if DEBUG
var target = new MemoryStream();
await stream.CopyToAsync(target).ConfigureAwait(false);
return target;
#endif
return stream;
}