Displaying a 404 Not Found Page for ASP.NET Core MVC

One of the best tutorials I found is this: https://joonasw.net/view/custom-error-pages

The summary is here:

1.
First add a controller like ErrorController then add this action to it:

[Route("404")]
public IActionResult PageNotFound()
{
    string originalPath = "unknown";
    if (HttpContext.Items.ContainsKey("originalPath"))
    {
        originalPath = HttpContext.Items["originalPath"] as string;
    }
    return View();
}

Note: You can add the action to another existing controller like HomeController.

2.
Now add the PageNotFound.cshtml view. Something like this:

@{
    ViewBag.Title = "404";
}

<h1>404 - Page not found</h1>

<p>Oops, better check that URL.</p>

3.
And the important part is here. Add this code to Startup class, inside Configure method:

app.Use(async (ctx, next) =>
{
    await next();

    if(ctx.Response.StatusCode == 404 && !ctx.Response.HasStarted)
    {
        //Re-execute the request so the user gets the error page
        string originalPath = ctx.Request.Path.Value;
        ctx.Items["originalPath"] = originalPath;
        ctx.Request.Path = "/error/404";
        await next();
    }
});

Note that it must be added before routing configs like app.UseEndpoints....

Leave a Comment

File not found.