How do I 301 redirect /Home to root?

后端 未结 1 1622
鱼传尺愫
鱼传尺愫 2021-01-22 05:50

Here is my route in Global.asax to remove /Home:

    routes.MapRoute(\"Root\", \"{action}/{id}\",
        new { controller = \"Home\", action = \"Index\", id = U         


        
相关标签:
1条回答
  • 2021-01-22 06:09

    If you want to allow this URL, you can do

    routes.MapRoute("Root", "Home",
         new { controller = "Home", action = "Index", id = UrlParameter.Optional });
    

    But you want redirection, and it does make most sense, so...

    Another thing you can do is create another controller Redirector and an action Home.

    public class RedirectorController : Controller
    {
        public ActionResult Home()
        {
            return RedirectPermanent("~/");
        }
    }
    

    Then you set the routes as:

    routes.MapRoute("Root", "Home",
            new { controller = "Redirector", action = "Home"});
    

    Remember to add the route at the top of your routes so that the generic routes don't match instead.

    Update:

    Another thing you can do is add this to the end of your routes:

    routes.MapRoute("Root", "{controller}",
        new { controller = "Home", action = "Index", id = UrlParameter.Optional });
    

    But this is not redirect still. So, can change the Redirector to be generic as...

    public class RedirectorController : Controller
    {
        public ActionResult Redirect(string controllerName, string actionName)
        {
            return RedirectToActionPermanent(actionName, controllerName);
        }
    }
    

    Then the route (which should be now at the bottom of all routes) will be:

    routes.MapRoute("Root", "{controllerName}",
            new { controller = "Redirector", action = "Redirect", 
                  controllerName = "Home", actionName = "Index" });
    

    So, it'll try to redirect to the Index action of a controller with the same name as /name. Obvious limitation is the name of the action and passing parameters. You can start building on top of it.

    0 讨论(0)
提交回复
热议问题