1

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

David McEleney
  • 3,397
  • 1
  • 26
  • 32
  • Could you share the `Configure` method in your Startup class to better understand where exactly your middleware is injected? – eduherminio Mar 12 '21 at 12:40
  • @eduherminio in `Configure`, `app.UseMiddleware();` It's running the middeware fine – David McEleney Mar 12 '21 at 12:43
  • I'm afraid that's now enough to determine what's going on. Please, have a read [here](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-5.0#middleware-order), it makes a huge difference the position you're injecting your middleware in. – eduherminio Mar 12 '21 at 13:47

0 Answers0