Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

ASP.NET Core 2.0 Error Pages

0.00/5 (No votes)
1 Sep 2017 1  
How to serve error pages in ASP.NET Core application. Continue reading...

Problem

How to serve error pages in ASP.NET Core application.

Solution

Starting from an empty project, created in a previous post, amend the Configure() method of Startup class to use middleware needed for error handling. Below, I’ve used a custom middleware (defined as lambda) to handle production exceptions:

public void Configure(
            IApplicationBuilder app,
            IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler(appBuilder =>
                {
                    appBuilder.Run(async context =>
                    {
                        var feature =
                            context.Features.Get();
                        var exception = feature.Error;
                        await context.Response.WriteAsync(
                            $"<b>Oops!</b> {exception.Message}");
                    });
                });
            }

            app.Run(async (context) =&gt;
            {
                throw new ArgumentException("T must be set");
                await context.Response.WriteAsync("Hello Error Handling!");
            });
        }

Alternatively, you could point to MVC controller/action, which would return a ViewResult:

app.UseExceptionHandler("/Error");

Discussion

It is really simple to configure middleware to setup error pages for both development and production environment.

The error page for development environment shows all the relevant details that developers require to resolve the issue. However, this page is not suitable for production/end-user, it gives too much information which could be used for malicious reasons.

There are two ways in which we can show user and production friendly error pages:

  1. Plug-in a middleware into UseExceptionHandler (which itself is a middleware). This gives a lot of flexibility on how to build an error response.
  2. Provide path to MVC controller/action and create error page using MVC views. Note that the path must starts with ‘/’.
    • It is better to use only static content in error pages, to avoid them throwing exception.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here