首页 文章

替换ASP.NET Core 1.0中间件中的响应流

提问于
浏览
3

我想在我的ASP.NET Core 1.0项目中编写自定义中间件,它将取代原始框架的Http响应流到我自己的,所以我将能够对它执行读/寻/写操作(原来不能在原来的2上) stream)在进一步的代码中,即在Actions或Filters中 .

我已经开始使用以下代码:

public class ReplaceStreamMiddleware
{
    protected RequestDelegate NextMiddleware;

    public ReplaceStreamMiddleware(RequestDelegate next)
    {
        NextMiddleware = next;
    }

    public async Task Invoke(HttpContext httpContext)
    {       
        using (var responseStream = new MemoryStream())
        {
            var fullResponse = httpContext.Response.Body;
            httpContext.Response.Body = responseStream;
            await NextMiddleware.Invoke(httpContext);
            responseStream.Seek(0, SeekOrigin.Begin);
            await responseStream.CopyToAsync(fullResponse);
        }   
    }
}

以下代码的问题是 sometimes fullResponse 流在调用 await responseStream.CopyToAsync(fullResponse); 时是 already closed 因此它抛出异常无法访问已关闭的Stream .

当我在浏览器中加载页面然后刷新时,这种奇怪的行为很容易被观察到, before it loads completely .

我想知道:

  • 为什么会这样?

  • 怎么预防呢?

  • 是我的解决方案一个好主意还是有另一种方法来替换响应流?

1 回答

  • 7

    例外不是来自 CopyToAsync . 它是's from one of your code'的来电者:

    您没有在 HttpContext 中恢复原始响应流 . 因此,无论谁调用您的中间件,都会收回已关闭的 MemoryStream .

    这是一些有效的代码:

    app.Use(async (httpContext, next) =>
    {
        using (var memoryResponse = new MemoryStream())
        {
            var originalResponse = httpContext.Response.Body;
            try
            {
                httpContext.Response.Body = memoryResponse;
    
                await next.Invoke();
    
                memoryResponse.Seek(0, SeekOrigin.Begin);
                await memoryResponse.CopyToAsync(originalResponse);
            }
            finally
            {
                // This is what you're missing
                httpContext.Response.Body = originalResponse;
            }
        }
    });
    
    app.Run(async (context) =>
    {
        context.Response.ContentType = "text/other";
        await context.Response.WriteAsync("Hello World!");
    });
    

相关问题