Mar*_*cki 3 asp.net-core asp.net-core-1.0 asp.net-core-middleware
我想在我的ASP.NET Core 1.0项目中编写自定义中间件,它将取代原始框架的Http响应流到我自己的,所以我将能够对它执行读/寻/写操作(原来不可能在原来的2)流)在进一步的代码中,即在动作或过滤器中.
我已经开始使用以下代码:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
用下面的代码的问题是,有时在fullResponse流已经关闭,在调用的时候await responseStream.CopyToAsync(fullResponse);所以它抛出一个异常,无法访问已关闭的流.
当我在浏览器中加载页面然后在完全加载之前刷新时,很容易观察到这种奇怪的行为.
我想知道:
例外不是来自你的CopyToAsync.它来自您的一个代码的调用者:
您没有恢复原始响应流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!");
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2522 次 |
| 最近记录: |