本文介绍了修改中间件响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的要求:编写一个中间件,该中间件可以过滤掉来自其他后续中间件(例如Mvc)的响应中的所有不良词。

My requirement: write a middleware that filters all "bad words" out of a response that comes from another subsequent middleware (e.g. Mvc).

问题:响应流式传输。因此,当我们从后续的中间件(已写入响应)回到我们的 FilterBadWordsMiddleware 时,我们来晚了……因为响应已经开始发送,产生众所周知的错误响应已经开始 ...

The problem: streaming of the response. So when we come back to our FilterBadWordsMiddleware from a subsequent middleware, which already wrote to the response, we are too late to the party... because response started already sending, which yields to the wellknown error response has already started...

因此,由于这是许多情况下的要求, -如何处理?

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

推荐答案

将响应流替换为 MemoryStream 防止其发送。修改响应后,返回原始流:

Replace a response stream to MemoryStream to prevent its sending. Return the original stream after the response is modified:

    public async Task Invoke(HttpContext context)
    {
        bool modifyResponse = true;
        Stream originBody = null;

        if (modifyResponse)
        {
            //uncomment this line only if you need to read context.Request.Body stream
            //context.Request.EnableRewind();

            originBody = ReplaceBody(context.Response);
        }

        await _next(context);

        if (modifyResponse)
        {
            //as we replaced the Response.Body with a MemoryStream instance before,
            //here we can read/write Response.Body
            //containing the data written by middlewares down the pipeline

            //finally, write modified data to originBody and set it back as Response.Body value
            ReturnBody(context.Response, originBody);
        }
    }

    private Stream ReplaceBody(HttpResponse response)
    {
        var originBody = response.Body;
        response.Body = new MemoryStream();
        return originBody;
    }

    private void ReturnBody(HttpResponse response, Stream originBody)
    {
        response.Body.Seek(0, SeekOrigin.Begin);
        response.Body.CopyTo(originBody);
        response.Body = originBody;
    }

这是一种解决方法,可能会导致性能问题。我希望在这里看到更好的解决方案。

It's a workaround and it can cause performance problems. I hope to see a better solution here.

这篇关于修改中间件响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 18:23