首页 > 解决方案 > How to change the http status code after starting writing to the HttpContext.Response.Body stream in ASP.NET Core?

问题描述

I often see that writing to the HttpContext.Response.Body stream is a bad practice (or using PushStreamContent or StreamContent as part of a HttpMessageResponse) cause then you cannot change the HTTP status code if there is something wrong happening.

Is there any workaround to actually perform async writing to the output stream while being able to change HTTP status code in case the operation goes wrong?

标签: c#.net.net-corestreamingasp.net-core-webapi

解决方案


是的。最佳实践是编写中间件。例如:

public class ErrorWrappingMiddleware
{
    private readonly RequestDelegate next;

    public ErrorWrappingMiddleware(RequestDelegate next)
    {
        this.next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await next.Invoke(context);
        }
        catch (Exception exception)
        {
            context.Response.StatusCode = 500;
            await context.Response.WriteAsync(...); // change you response body if needed
        }
    }
}

并将它们注入您的管道

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
{
...
app.UseMiddleware<ErrorWrappingMiddleware>();
...
}

当然,您可以根据需要更改中间件中的逻辑,包括根据需要更改响应代码。此外,您可以抛出自己的异常类型,例如MyOwnException,在中间件中捕获然后调用您自己的与您的异常相关的逻辑。


推荐阅读