简体   繁体   English

在 ASP.NET 核心中间件中设置响应状态

[英]Set response status in ASP.NET core middleware

I have a middleware, which hides exception from client and returns 500 error in case of any exception:我有一个中间件,它隐藏客户端的异常并在出现任何异常时返回 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
            }
        }
    }
}

My problem is that, if I set response status before writing body, client will see this status, but if I set status after writing message to body, client will receive response with status 200.我的问题是,如果我在写入正文之前设置响应状态,客户端将看到此状态,但是如果我在将消息写入正文后设置状态,客户端将收到状态为 200 的响应。

Could somebody explain me why it's happening?有人可以解释我为什么会这样吗?

PS I am using ASP.NET Core 1.1 PS 我使用的是 ASP.NET Core 1.1

That's by design, when you know how HTTP works.这是设计使然,当您知道 HTTP 的工作原理时。

Headers are in the beginning of the datastream (see wiki example ).标头位于数据流的开头(参见wiki 示例)。 Once you send the data, you can't change/modify the headers, because the data has already been sent over the wire.一旦发送数据,就不能更改/修改标头,因为数据已经通过网络发送了。

You would have to buffer the whole response if you want to set it later on, but this increases the memory usage.如果您想稍后设置它,您将不得不缓冲整个响应,但这会增加内存使用量。 Here is a sample on how to swap the stream for a memory stream.这是一个关于如何将流交换为内存流的示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM