Search code examples
c#.net.net-corestreamingasp.net-core-webapi

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?


Solution

  • 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.