Create Configurable Error Pages in ASP.NET Core

Jun 27, 2016     Viewed 6314 times    3 Comments
Posted in #Configuration  #Diagnostics 

The ASP.NET Core came up with many middlewares that handle the exception nicely instead of YSOD, almost of them are available in Diagnostics Repository.

If we are looking to the previous versions of ASP.NET, we will notice that ASP.NET has a good way to create a configurable and customizable error pages via Web.Config as the following:

    <compilation debug="true" />
    <customErrors mode="On" defaultRedirect="DefaultErrorPage.aspx">
      <error statusCode="401" redirect="Http401ErrorPage.aspx"/>
      <error statusCode="403" redirect="Http403ErrorPage.aspx"/>
      <error statusCode="404" redirect="Http404ErrorPage.aspx"/>
      <error statusCode="500" redirect="Http500ErrorPage.aspx"/>

With that I decide to write a small blog post describing how can we achieve that in ASP.NET Core.

First of all we need to define the error pages in a file (JSON in our case) as the following:

"ErrorPages": {
  "401": "/Error/Http401ErrorPage",
  "403": "/Error/Http403ErrorPage",
  "404": "/Error/Http404ErrorPage",
  "500": "/Error/Http500ErrorPage"

after that we can fetch the values of status codes & paths easily with the help of Configuration APIs that provided by ASP.NET Core itself.

public IConfigurationRoot Configuration { get; }

internal static IDictionary ErrorPages { get; } = new Dictionary();

The Configuration property will hold the configuration data and the ErrorPages will contains the details of the error pages.

Then we need to read the data from the JSON file and write them into the declared properties.

var builder = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)

Configuration = builder.Build();

foreach (var c in Configuration.GetSection("ErrorPages").GetChildren())
    var key = Convert.ToInt32(c.Key);
    if (!ErrorPages.Keys.Contains(key))
        ErrorPages.Add(key, c.Value);

Now it's time to create a piece of middleware that handle the HTTP errors and map them into the predefined paths.

public class CustomErrorPagesMiddleware
    private readonly RequestDelegate _next;
    private readonly ILogger _logger;

    public CustomErrorPagesMiddleware(ILoggerFactory loggerFactory, RequestDelegate next)
        _next = next;
        _logger = loggerFactory.CreateLogger();

    public async Task Invoke(HttpContext context)
            await _next(context);
        catch (Exception ex)
            _logger.LogError(0, ex, "An unhandled exception has occurred while executing the request");

            if (context.Response.HasStarted)
                _logger.LogWarning("The response has already started, the error page middleware will not be executed.");
                context.Response.StatusCode = 500;
            catch (Exception ex2)
                _logger.LogError(0, ex2, "An exception was thrown attempting to display the error page.");
            var statusCode = context.Response.StatusCode;

            if (Startup.ErrorPages.Keys.Contains(statusCode))
                context.Request.Path = Startup.ErrorPages[statusCode];
                await _next(context);

The code is straightforward it reads the StatusCode from the Response object and looking for it in the predefined codes and if there's a match it changes the Path of the Request object to the one in the JSON file. 

Last but not least we need write an extension to the IApplicationBuilder interface

public static class BuilderExtensions { public static IApplicationBuilder UseCustomErrorPages(this IApplicationBuilder app) { return app.UseMiddleware<CustomErrorPagesMiddleware>(); } }

Finally use it in the Configure method in the Startup class like this


You can download the source code for this post from my CustomErrorPages repository on GitHub.

Twitter Facebook Google + LinkedIn


Paul H (8/18/2016 5:28:28 PM)

How does this compare to the built-in error handling using app.UseStatusCodePagesWithReExecute or app.UseStatusCodePagesWithRedirects?

Hisham Bin Ateya (8/28/2016 5:27:15 AM)

@Paul the CustomErrorPagesMiddleware can use redirect or re-execute the request behind the scene like the built-in middlewares, but the intent is to have an easy way to configure the error pages like what we have seen in Wen.Config.

WEB MAsters Eye (12/15/2016 9:58:08 PM)

If You have any problems with Error pages.. Than just visit our site.. And consult with our developers..
You will get your solution...

Leave a Comment