Set response status in ASP.NET middleware

I have middleware that hides an exception from the client and returns 500 errors in case of any exception:

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 the status of the response before recording the body, the client will see this status, but if I set the status after writing the message to the body, the client will receive a response with the status 200.

Can someone explain to me why this is happening?

PS I am using ASP.NET Core 1.1

+5
source share
1 answer

This is by design when you know how HTTP works.

The headers are at the beginning of the data stream (see wiki example ). After sending the data, you cannot change / change the headers, because the data has already been sent by wire.

You will need to buffer the whole response if you want to install it later, but this will increase memory usage. Here's a sample on how to change the stream for a memory stream.

+8
source

Source: https://habr.com/ru/post/1263633/


All Articles