Okay, so you’ve probably come across tons of broken links on our enormous world wide web, and it gets even more frustrating when there aren’t any links or buttons redirecting to a working page. However, the hard truth is, in reality, errors are inevitable. Whether they occur through wrong user input, or simply just one or two bugs in your code, they are simply just inevitable.
This article explains perhaps the most efficient way to set up custom error pages for your ASP.NET core web Application. Using custom error pages is immensely satisfying, as opposed to having blank pages, default browser-specific pages, or using the default error pages provided by ASP.NET core.
How it works
So, let’s say we run our application and go to a page which doesn’t exist. Once a request gets all the way through to the end of our MVC pipeline, and we have no middleware handling the request, we get the dreaded 404 error (or “Page not found”, if you will). Some browsers might be nice enough to display an error page, others will just leave a blank page, leaving your user slightly nonplussed – Not exactly the kind of thing that makes great user experiences great, is it?.
Setting up our custom error page
Creating the Controller class
To Begin setting up our error page, we need to create a controller to respond to the request. To keep this example as simple as possible, I'm going to create a simple MVC controller class – as a matter of fact, I will be using the default template provided by visual studio (2015), and then adding a URI template for the route.
for a more detailed example, we can go all the way to implement logging, using the ILogger and IStatusCodeReExecuteFeature interfaces, logging the url that the request came through.
Creating the view
Next we create the view for the index action of our StatusCode Controller class.
For a simple view, we could have.
For a more dynamic view, we could go a bit further.
you get the idea. Feel free to include more Http status code cases.
Setting up the middleware
Once we are done with the controller and the view, we finish up by setting up a middleware to handle the request in the pipeline, in the configure method of our startup class. Like so.
And you're done!
You can test your error pages by generating errors yourself. Easily begin by navigating to a non-existent page, to try out a 404 error like so.
The entire code sample used can be found on my github here . Good luck !