Change middleware response

My requirement: write a middleware that filters out all the "bad words" from a response that comes from other downstream middleware (like Mvc).

Problem: streaming the response. So when we go back to ours FilterBadWordsMiddleware

from the subsequent middleware already written in the response, we are late to the party ... because the response has already started to send, leading to a known error response has already started

...

So, since this is a requirement in many different situations - how to deal with it?

+3


source to share


1 answer


Replace the response stream with MemoryStream

to prevent it from being sent. Returning the original stream after changing the answer:

public class EditResponseMiddleware
{
    private readonly RequestDelegate _next;

    public EditResponseMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        var originBody = context.Response.Body;

        var newBody = new MemoryStream();

        context.Response.Body = newBody;

        await _next(context);

        newBody.Seek(0, SeekOrigin.Begin);

        string json = new StreamReader(newBody).ReadToEnd();

        context.Response.Body = originBody;

        await context.Response.WriteAsync(modifiedJson);
    }
}

      



This is a workaround and can cause performance issues. I hope to see a better solution here.

+4


source







All Articles