【发布时间】:2020-04-02 09:39:48
【问题描述】:
我有一个中间件,它对客户端隐藏异常并在出现任何异常时返回 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
【问题讨论】:
标签: asp.net asp.net-core