My app is running ASP.NET Core RC2
, and I'm confused as to how the status code and exception handler middleware works.
My app is configured with the following middleware.
app.UseStatusCodePagesWithReExecute("/Error/Status/{0}");
app.UseExceptionHandler("/Error/ServerError");
The controller handles which view it should return:
[HttpGet]
public IActionResult Status(int id)
{
switch (id)
{
case 404:
return View("404");
case 400:
return View("400");
case 500:
return View("500");
default:
return View("501");
}
}
[HttpGet]
public IActionResult ServerError()
{
return View();
}
When I navigate to an unknown URL it will return the 404 page
as expected from the Status action.
When I navigate to an action that throws an exception it will navigate to /Error/ServerError
and not the 500 page
from the Status action.
public IActionResult ThrowException()
{
throw new Exception();
}
If I navigate to an action that returns StatusCodeResult(500);
it will return the 500 page
from the Status action.
[HttpGet]
public IActionResult Error500()
{
return new StatusCodeResult(500);
}
What confuses me is that the console shows that both results return 500 (Internal Server Error)
but depending on how they are returned they will navigate to a different page based on the middleware.
Why is this?
When I navigate to an action that throws an exception it will navigate to /Error/ServerError and not the 500 page from the Status action.
This is expected because the ExcetionHandlerMiddleware handles unhandled exceptions and also is registered after
the status code pages middleware and so get executed first when the response goes out. I believe even if you re-order these middlewares you would not see a difference in behavior because status code pages middleware looks for a status code on the outgoing HttpResponse instance and in case of unhandled exceptions this might not be set.
Updated: Responding to a comment. You can do something like below:
[HttpGet]
public IActionResult ServerError()
{
var exceptionHandlerFeature = HttpContext.Features.Get<IExceptionHandlerFeature>();
if (exceptionHandlerFeature != null)
{
var exception = exceptionHandlerFeature.Error;
//TODO: log the exception
}
return View("500");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With