Creating Custom Error Pages in ASP.NET core

Introduction

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 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. This 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 our pipeline.

read more