Kaan Öztürk
Kaan Öztürk

Reputation: 442

Can not read StreamReader correctly

I have a middleware to read the request and response as follows

public class FooMiddleware
{
    private readonly RequestDelegate _next;

    public FooMiddleware(RequestDelegate next)
    {
        _next = next;
    }
    public async Task Invoke(HttpContext httpContext)
    {
        var originalBodyStream = httpContext.Response.Body;

        using var requestBody = new MemoryStream();
        await httpContext.Request.Body.CopyToAsync(requestBody);
        requestBody.Seek(0, SeekOrigin.Begin);

        string requestContent = await new StreamReader(requestBody, Encoding.UTF8).ReadToEndAsync();
        requestBody.Seek(0, SeekOrigin.Begin);

        using var tempStream = new MemoryStream();
        httpContext.Response.Body = tempStream;

        await _next.Invoke(httpContext);

        tempStream.Seek(0, SeekOrigin.Begin);

        var responseContent = await new StreamReader(httpContext.Response.Body, Encoding.UTF8).ReadToEndAsync();
        tempStream.Seek(0, SeekOrigin.Begin);

        await tempStream.CopyToAsync(originalBodyStream);

        httpContext.Response.Body = originalBodyStream;
    }

}

When I checked responseContent, there is no readable content.

enter image description here

Current HttpContext.Response.ContentType value is application/json charset=utf-8

I've tried different encoding types like Default, UTF-8, Unicode... but I can not get readable content.

With this code like this, I changed return Ok(response); with return Ok(JsonConvert.SerializeObject(response)) in controller method then I can get readable content but I don't think it's the right solution.

How can I fix it ?

Upvotes: 0

Views: 71

Answers (0)

Related Questions