I have a middleware, which hides exception from client and returns 500 error 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 response status before writing body, client will see this status, but if I set status after writing message to body, client will receive response with status 200.
Could somebody explain me why it's happening?
P.S. I am using ASP.NET Core 1.1