ASP.NET Core 2.0 Status Code Pages

Problem

How to create error pages for specific HTTP status codes in ASP.NET Core

Solution

Create an empty project and update Startup to add middleware for Status Code Pages:

Note: the {0} is substituted with the HTTP status code that triggered the execution middleware

Add Errors controller to catch status code errors:

Add a view for Index view and display error details:

Add Home controller to return status codes:

Add a view for Index view:

Run and click one of the links, you’ll the view from Errors controller, note however that the URL doesn’t change:

The request made shows the status code error too:

Discussion

Exception handling middleware (as discussed here) will catch unhandled exceptions however if you want to display error pages for individual HTTP status codes then framework provides another middleware for this purpose.

When configuring the middleware you have option to either re-execute or re-direct the request. The above solution shows re-execute, where the server rewrites the request. The result is that URL reflects the path browsed by the user, rather than the path to errors page.

Another option is to configure re-direct when setting up middleware:

However now the browser will display the path to errors page:

And as it’s a redirect, server will first send a 302 (Found) to the browser, which will make a subsequent request to the errors page:

Source Code

GitHub: https://github.com/TahirNaushad/Fiver.Mvc.StatusError

Leave a Reply