简体   繁体   中英

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?

Yes. Best practise is write Middleware. For example:

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
        }
    }
}

and inject them to your pipeline

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

And of course you can change your logic in your midleware as you wish, include change Response Code as you wish. Also, you can throw you own exception type, like MyOwnException , catch then in middleware and invoke you own logic wich related to your exception.

Don't call next. Invoke after the response has been sent to the client. Changes to HttpResponse after the response has started, throw an exception.

For example, changes such as setting headers and a status code throw an exception. Writing to the response body after calling next may cause a protocol violation, ie, writing more than what's specified in Content-Length header.

It might corrupt the body format, like writing an HTML footer to a CSS file.

HasStarted is a useful hint to indicate if headers have been sent or the body has been written to.

Check this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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