404 is a frequently-seen status code that tells a Web user that a requested page is "Not found." 404 and other status codes are part of the Web's Hypertext Transfer Protocol ( HTTP ), written in 1992 by the Web's inventor, Tim Berners-Lee. He took many of the status codes from the earlier Internet protocol for transferring files, the File Transfer Protocol ( FTP .)

What to Do If You Get a 404

If the site no longer exists, there's nothing you can do. However, it only takes one mistyped character to result in a 404. See whether the ".htm" should be an ".html" or vice versa. If you're linking from a Web site, you can do a "View source" to make sure it wasn't miscoded. Whether or not it is, you may want to send a note to the Webmaster so that the link can be fixed for the next users.

In this tutorial, I will show you how to handle 404 error in ASP.NET Core 1.0. Prior versions of ASP.NET Core 1.0, have custom errors for error handling. With ASP.NET Core 1.0 and MVC, you can do the error handling via Middlwares. HTTP 404 is a very common error which comes when server can’t find the requested resource. In this post, we will see different ways to handle HTTP 404 error in ASP.NET Core 1.0 and MVC.

How to handle 404 error in ASP.NET Core 1.0


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. You can read this excellent post The Startup.cs File in ASP.NET Core 1.0. to know more about startup.cs. And within the startup.cs file, you will also find static void main() which generally you use with windows/console applications. Read my post Why static void main in ASP.NET 5 startup.cs

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.

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 another middle. 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("/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. The {0} is nothing but the HTTP status error code. Below is the implementation of Errors action method.

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

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");
}

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.


HostForLIFE.eu ASP.NET Core 1.0 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.