Displaying a custom error page in ASP.NET Core is very simple, but there are some pitfalls to avoid.

To display an error page (error 500), simply write the following line of code:


app.UseExceptionHandler("Error"); 

To view the other types of errors (page 404, etc.) simply call the following method:


app.UseStatusCodePagesWithRedirects("/StatusCode?code={0}"); 

Unfortunately, I'm not sure. this n’It's not that simple ! If your ASP.NET Core website hosts WebAPIs they will also be affected by these changes

Excludes APIs from custom error pages

In such cases, I am fortunate to be able to invoke A wizard from ASP.NET Core In addition, I highly recommend his series of articles on the use ofUser defined function with EF Core.

Change the management of the StatusCode

To change the display of the page managing the StatusCode so we have to go through a StatusCodePagesOptions And exclude all roads that start with api”.


app.UseStatusCodePages(new StatusCodePagesOptions()
{
            HandleAsync = ctx =>
            {
                if (ctx.HttpContext.Request.Path != null &&
                !ctx.HttpContext.Request.Path.Value.StartsWith("api"))
                {
                    ctx.HttpContext.Response.Redirect($"/StatusCode?code={ctx.HttpContext.Response.StatusCode}");
                    return Task.CompletedTask;
                }

                return ctx.Next.Invoke(ctx.HttpContext);
            }
});

Changes in error management

For error management we will use the same logic, all segments starting with api will be excluded.

Please note: that we use the method UseWhen This means that middleware can only be used in certain cases.


app.UseWhen(ctx => !ctx.Request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase), cfg =>
                 cfg.UseExceptionHandler("/Error")

Happy coding 🙂

To go further: