Why is the exception redirected to different pages?

My application runs ASP.NET Core RC2 , and I am confused about how middleware works for the status code and the exception handler.

My application is configured with the following middleware.

 app.UseStatusCodePagesWithReExecute("/Error/Status/{0}"); app.UseExceptionHandler("/Error/ServerError"); 

The controller processes the view to be returned:

 [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 404 page , as expected, from the Status action.

When I go to the action that throws the exception, it will be moved to /Error/ServerError , not the 500 page from the Status action.

 public IActionResult ThrowException() { throw new Exception(); } 

If I go to an action that returns StatusCodeResult(500); , it will return 500 page from the Status action.

 [HttpGet] public IActionResult Error500() { return new StatusCodeResult(500); } 

What bothers me is that the console shows that both results return 500 (Internal Server Error) , but depending on how they are returned, they will be moved to another page based on middleware.

enter image description here

Why is this?

+5
source share
1 answer

When I go to the action that throws the exception, it will be moved to / Error / ServerError, not 500 pages from the Status action.

This is expected because ExcetionHandlerMiddleware handles unhandled exceptions, and also after middleware code pages are registered, and therefore runs first when the response goes blank. I believe that even if you change the order of these intermediates, you will not see any difference in behavior, because the middleware pages of the code code look for the status code on the outgoing HttpResponse instance, and this may not be specified in the case of unhandled exceptions.

Updated: Reply to 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"); } 
+4
source

All Articles