I've got a middleware class that logs path, time taken & response codes.
public async Task InvokeAsync(HttpContext context)
{
var sw = Stopwatch.StartNew();
try
{
await _next(context); // Controller throws an exception, un caught.
}
finally
{
// at this point, context.Response.StatusCode is 200. but the response to client is 500.
_logger.LogInformation("{Path} - {StatusCode} - {TimeTaken}",
context.Request.Path, context.Response.StatusCode, sw.ElapsedMilliseconds);
}
}
When an error occurs, context.Response.StatusCode
has a value of 200. I'd have expected it to be 500 (even though I'm not explicitly returning InternalServerError
).
If I get a 400, 404, or genuine 200 the status code is correct.
But when an exception is thrown, the middleware still gets a 200 in context.Response.StatusCode, but the consuming client gets a 500 as expected.
Thanks, David