Miguel Cordero
Miguel Cordero

Reputation: 141

How to route Error 404 to a default View?

I have a project in .NET Core 1.1 whit MVC architecture, and I want to redirect when in an incorrect URL (Status Code: 404; Not Found) to redirect to an error View that I have already created.

In another project with just one controller, I made it work correctly with this:

        [Route ("/Home/Error")]
        public IActionResult Error()
        {
            ViewBag.Title = "About Us";

            return View();
        }
        [Route("/{a}/{*abc}")]
        [HttpGet]
        public IActionResult Err(string a)
        {
            return RedirectToAction("Error", "Home");
        }

and having in the start-up:

app.UseMvc(routes =>
{     routes.MapRoute(
            name: "Default",
            template: "{controller=Home}/{action=GetDocument}/{id?}");
});

But if in THIS PROJECT, with 4 controllers, with this configuration on the start-up:

 app.UseMvc(routes =>
    {   routes.MapRoute(
             name: "Default",
             template: "{controller}/{action}/{id?}",
             defaults: new { controller = "Home", action = "IndexB" }
          );
     );

and this code on the HomeController or all the controllers (I have tried it both):

        [Route("/Home/Error")]
        public IActionResult Error()
        {
            ViewBag.Title = "About Us";

            return View();
        }
        [Route("/{a}/{*abc}")]
        [HttpGet]
        public IActionResult Err(string a)
        {
            return RedirectToAction("Error", "Home");
        }

With the first code in another project works like a charm, it goes where it has to go but with a non existing URL goes to the Error Page.

But in THIS PROJECT with the second code I get redirected always to the error page no matter what.

Upvotes: 1

Views: 2734

Answers (2)

Muhammad Aqib
Muhammad Aqib

Reputation: 849

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.

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();

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}");
public IActionResult Errors(string errCode) 
{ 
  if (errCode == "500" | errCode == "404") 
  { 
    return View($"~/Views/Home/Error/{errCode}.cshtml"); 
  }

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

Upvotes: 2

Lalji Dhameliya
Lalji Dhameliya

Reputation: 1769

if you redirect to default view for 404 add custom middleware delegate in Configure method of Startup.cs file.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
        app.Use(async (context, next) =>
        {
            await next();
            if (context.Response.StatusCode == 404)
            {
                context.Request.Path = "/home/notfound";
                await next();
            }
        });

        app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
}

Here app.Use(async (context, next) => ... is your middleware delegate that check if your response statuscode 404 then set your default path for redirect context.Request.Path = "/home/notfound";. and you can also set default view for others status code like 500 etc.

i hope it helps you and let me know if require any more information. :)

Upvotes: 2

Related Questions