修改中间件响应

时间:2017-06-12 20:16:35

标签: asp.net-core .net-core asp.net-core-middleware

我的要求:编写一个中间件,用于过滤来自其他后续中间件(例如Mvc)的响应中的所有“坏词”。

问题:响应的流式传输。因此,当我们从已经写入响应的后续中间件回到我们的FilterBadWordsMiddleware时,我们已经迟到了派对......因为响应已经开始发送,这导致了众所周知的错误{{1} } ...

所以,因为这是许多不同情况下的要求 - 如何处理它?<​​/ p>

4 个答案:

答案 0 :(得分:7)

将响应流替换为pip install --upgrade pip 以阻止其发送。修改响应后返回原始流:

MemoryStream

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

答案 1 :(得分:7)

基于我使用的代码的简单版本:

/// <summary>
/// The middleware Invoke method.
/// </summary>
/// <param name="httpContext">The current <see cref="HttpContext"/>.</param>
/// <returns>A Task to support async calls.</returns>
public async Task Invoke(HttpContext httpContext)
{
    var originBody = httpContext.Response.Body;
    try
    {
        var memStream = new MemoryStream();
        httpContext.Response.Body = memStream;

        await _next(httpContext).ConfigureAwait(false);

        memStream.Position = 0;
        var responseBody = new StreamReader(memStream).ReadToEnd();

        //Custom logic to modify response
        responseBody = responseBody.Replace("hello", "hi", StringComparison.InvariantCultureIgnoreCase);

        var memoryStreamModified = new MemoryStream();
        var sw = new StreamWriter(memoryStreamModified);
        sw.Write(responseBody);
        sw.Flush();
        memoryStreamModified.Position = 0;

        await memoryStreamModified.CopyToAsync(originBody).ConfigureAwait(false);
    }
    finally
    {
        httpContext.Response.Body = originBody;
    }
}

答案 2 :(得分:6)

很遗憾,我的分数太低,因此我无法发表评论。 因此,我只想发布我对出色的顶级解决方案的扩展,以及对.NET Core 3.0+的修改

首先

context.Request.EnableRewind();

已更改为

context.Request.EnableBuffering();

在.NET Core 3.0 +

这是我读取/写入正文内容的方式:

首先是一个过滤器,所以我们只修改我们感兴趣的内容类型

private static readonly IEnumerable<string> validContentTypes = new HashSet<string>() { "text/html", "application/json", "application/javascript" };

这是一种将诸如[[[Translate me]]]之类的文本转换为译文的解决方案。这样,我可以标记所有需要翻译的内容,读取我们从翻译器获取的po文件,然后在输出流中进行翻译替换-不管块文本是否在剃刀视图中,javascript管他呢。 有点像TurquoiseOwl i18n软件包,但是在.NET Core中,不幸的是,该出色的软件包不支持。

...

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

    var contentType = context.Response.ContentType?.ToLower();
    contentType = contentType?.Split(';', StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();   // Filter out text/html from "text/html; charset=utf-8"

    if (validContentTypes.Contains(contentType))
    {
        using (var streamReader = new StreamReader(context.Response.Body))
        {
            // Read the body
            context.Response.Body.Seek(0, SeekOrigin.Begin);
            var responseBody = await streamReader.ReadToEndAsync();

            // Replace [[[Bananas]]] with translated texts - or Bananas if a translation is missing
            responseBody = NuggetReplacer.ReplaceNuggets(poCatalog, responseBody);

            // Create a new stream with the modified body, and reset the content length to match the new stream
            var requestContent = new StringContent(responseBody, Encoding.UTF8, contentType);
            context.Response.Body = await requestContent.ReadAsStreamAsync();//modified stream
            context.Response.ContentLength = context.Response.Body.Length;
        }
    }

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

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

答案 3 :(得分:0)

在这里可以找到“真实的”生产方案:tethys logging middeware

如果您遵循链接中显示的逻辑,请不要忘记在调用httpContext.Request.EnableRewind()_next(httpContext)名称空间的扩展方法)之前添加Microsoft.AspNetCore.Http.Internal