Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 524
Natalie Perret Avatar asked Oct 28 '25 05:10

Natalie Perret


1 Answers

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.

like image 100
Sergey Shulik Avatar answered Oct 29 '25 21:10

Sergey Shulik