Search code examples
asp.netasp.net-mvcasp.net-mvc-routing

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.


Solution

  • 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. :)