1/21/2019

Custom Error Pages in ASP.NET Core MVC

By: Nicklas Møller Jepsen

The default ASP.NET Core MVC template is not providing any good user friendly error pages. If you are developing a web app you might want to add your own custom error pages to handle situations like the user requesting a page that does not exists or show a user friendly custom error page. Here is how to set up custom error pages in ASP.NET Core MVC.

Configure the middleware

First add the app.UseStatusCodePagesWithReExecute("/Error/{0}"); This tells your app that it should go to the Error route and pass the HTTP status code as a route parameter. It should look something like this:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseStatusCodePagesWithReExecute("/Error/{0}");

    app.UseStaticFiles();
    app.UseAuthentication();
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");

    });
}

Create an endpoint to handle each HTTP status code

There are several ways to achieve this - for simplicity I have choosen to setup an endpoint that is called when HTTP status code 404 is occurring, when a page is not found. I have created an ErrorController and it looks like so:

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Proxus.Web.Controllers
{
    [AllowAnonymous] // Only needed if authorization is set up globally for the app
    [Route("Error")]
    public class ErrorController : Controller
    {
        [Route("404")]
        public IActionResult NotFound()
        {
            return View();
        }
    }
}

As you might be able to tell from the code, the above code is dependent on a View named NotFound present in the Views folder of the solution. You can put what ever you want inside that view, here is mine:

<div class="page-header error-page header-filter" style="background-image: url('/assets/images/black-and-white-black-and-white-challenge-262488.jpg')">
    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <h1 class="title">404</h1>
                <h2 class="description">Page not found :(</h2>
                <h4 class="description">Ooooups! Looks like we are unable to find that for you.</h4>
                
            </div>
        </div>
    </div>
</div>

You can see it in action right here

Hopefully your user will never end up on your custom error page :)

Thanks for reading!