Search code examples
c#asp.net-core-8

Console outputs the following line incorrectly


.NET 8

I have a Middleware that reads the request response:

public async Task InvokeAsync(HttpContext context)
{
    var originalBodyStream = context.Response.Body;

    using (var responseBody = new MemoryStream())
    {
        context.Response.Body = responseBody;

        await _next(context);

        context.Response.Body.Seek(0, SeekOrigin.Begin);
        var responseText = await new StreamReader(context.Response.Body).ReadToEndAsync();
        context.Response.Body.Seek(0, SeekOrigin.Begin);

        Console.WriteLine("Response Body:");
        Console.WriteLine(responseText);

        await responseBody.CopyToAsync(originalBodyStream);
    }
}

And I made a test controller, which is similar in functionality to the real case:

[HttpGet("sample")]
public IActionResult GetSample()
{
    var s = "[\r\n {    \"id\": \"test\",\r\n \"id\": \"test\"   } ]";
    return Content(s, "application/json; charset=utf-8");
}

This controller returns the correct result:

correct

But when I use the following line, I get an incorrect response:

[HttpGet("sample")]
public IActionResult GetSample()
{
    var s = "[\r\n    {\r\n        \"id\": \"test\",\r\n        \"tt\": \"213\",\r\n        \"nn\": \"33\"\r\n    }\r\n]";
    return Content(s, "application/json; charset=utf-8");
}

incorrect

The response is displayed correctly in Postman postman


Solution

  • Thank you all for the feedback!

    I solved the problem by deleting a line from Program.cs:

    app.UseResponseCompression();