Skip to main content
How to handle 404 error in ASP.NET Core 1.0

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. 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("/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.

If you come across any other solution, please mention in comments section or send it on twitter/facebook. All these solutions are based on RC1 release of ASP.NET Core. So if anything changes or broken please let us know. Keep visiting for updates and share this in your network.

PS: If you found this content valuable and want to return the favour, then Buy Me A Coffee

5 thoughts to “How to handle 404 error in ASP.NET Core 1.0”

  1. Hi, Dmitry

    with [HttpGet(“/Home/Errors/{statusCode}”)] above controller’s “Error” method, method will be called only with initial GET request and not with other types of request (POST, DELETE, PUT, HEAD, etc.). To support other types of request you must set [Route(“/Home/Errors/{statusCode}”)] instead of [HttpGet(…)]:

    [Route(“/Home/Errors/{statusCode}”)]
    public IActionResult Errors(string statusCode)
    {…

    You can check this in post https://www.devtrends.co.uk/blog/handling-errors-in-asp.net-core-web-api and read comments.

    Br,
    Branislav

    1. I’m sorry. I forgot to add attribute. Without it status code didn’t come.

      [HttpGet(“/Home/Errors/{statusCode}”)]
      public IActionResult Errors(string statusCode)
      {…

  2. I was facing an issue while redirecting to a View in a different folder. After googling, I came to your page and found this line: return View(“~/Views/Shared/Error.cshtml”);

    Adding .cshtml was the solution and this post saved my time. Thanks! for posting.

    Thanks!
    Balal

Leave a Reply

Your email address will not be published. Required fields are marked *