I have checked that some users experience this error 404 when deploying ASP.NET Core applications and I decide to write this tutorial. I hope it will fix the issue.

Fix 404 Error ASP.NET Core

I found 2 ways to handle 404 error. In fact using these solution you can handle any HTTP status code errors. To handle the error, both the solution are using configure() method of Startup.cs class. For those who are not aware about Startup.cs, it is entry point for application itself.

Solution 1

Now coming back to our solution 1, within configure method define a custom middleware via app.Use which checks for status code value in response object. And if is 404 then it redirects to Home controller. See highlighted code.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.UseApplicationInsightsRequestTelemetry();
    app.Use(async (context, next) =>
    {
        await next();
        if (context.Response.StatusCode == 404)
        {
            context.Request.Path = "/Home"; 
            await next();
        }
    });

    app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());
    app.UseApplicationInsightsExceptionTelemetry();
    app.UseStaticFiles();
    app.UseIdentity();
    // To configure external authentication please see http://go.microsoft.com/fwlink/?LinkID=532715
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

Solution 2

The other solution is to use a built-in middlware StatusCodePagesMiddleware. This middleware can be used to handle the response status code is between 400 and 600. This middleware allows to return a generic error response or allows you to also redirect to any controller action or another middleware. See below all different variations of this middleware.

app.UseStatusCodePages();

// app.UseStatusCodePages(context => context.HttpContext.Response.SendAsync("Handler, status code: " + context.HttpContext.Response.StatusCode, "text/plain"));
// app.UseStatusCodePages("text/plain", "Response, status code: {0}");
// app.UseStatusCodePagesWithRedirects("~/errors/{0}"); // PathBase relative
// app.UseStatusCodePagesWithRedirects("~/errors/{0}"); // PathBase relative
// app.UseStatusCodePagesWithRedirects("/base/errors/{0}"); // Absolute
// app.UseStatusCodePages(builder => builder.UseWelcomePage());
// app.UseStatusCodePagesWithReExecute("/errors/{0}");

Now to handle the 404 error, we shall use app.UseStatusCodePagesWithReExecute which accepts a path where you wish to redirect.

app.UseStatusCodePagesWithReExecute("/Home/Errors/{0}");

So we are redirecting here to Home Controller and Errors action method.

public IActionResult Errors(string errCode)
{
    ViewData["ErrorID"] = "The following error " + errCode + " occured";
    return View("~/Views/Shared/Error.cshtml");
}

The {0} is nothing but the HTTP status error code. Below is the implementation of Errors action method.It adds the status code in ViewData and then returns to Error.cshtml shared view. You can also return to specific error page based on the error code.

public IActionResult Errors(string errCode) 
{
    if (errCode == "500" | errCode == "404") 
    {
      return View($"~/Views/Home/Error/{errCode}.cshtml"); 
    }

    return View("~/Views/Shared/Error.cshtml"); 
}

Conclusion

So, if the error code is 500 or 404 then return to Home/Error/500.cshtml or 404.cshtml.

You must have seen on many websites, forums about app.UseErrorPage(); to handle the errors. But this is no longer available with RC1 release of ASP.NET Core 1.0. This was available until beta 5 or 6.

Leave a comment

Your email address will not be published.