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 HTTP status code that triggered the execution middleware.

Add Errors Controller to catch the status code errors.

Add a view for Index View and display error details.

Add Home controller to return the status codes.

Add a view for Index View.

Run and click one of the links. You’ll get the view from Errors controller. Do 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 an 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

 

Next Recommended Readings