我有一个中间件,它隐藏了客户端的异常,并在出现任何异常时返回500错误:
public class ExceptionHandlingMiddleware
{
private readonly RequestDelegate _next;
public ExceptionHandlingMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next.Invoke(context);
}
catch (Exception exception)
{
var message = "Exception during processing request";
using (var writer = new StreamWriter(context.Response.Body))
{
context.Response.StatusCode = 500; //works as it should,response status 500
await writer.WriteAsync(message);
context.Response.StatusCode = 500; //response status 200
}
}
}
}
我的问题是,如果我在写主体之前设置响应状态,客户端将看到此状态,但如果我在向主体写入消息后设置状态,则客户端将收到状态为200的响应.
有人可以解释一下为什么会这样吗?
附:我正在使用ASP.NET Core 1.1
解决方法
当你知道HTTP是如何工作的时候那就是设计.
标头位于数据流的开头(见wiki example).发送数据后,您无法更改/修改标头,因为数据已通过网络发送.
如果要稍后设置它,则必须缓冲整个响应,但这会增加内存使用量.这里有关于如何将流交换为内存流的a sample.
