How do I 301 redirect /Home to root?

我是研究僧i 提交于 2019-12-02 02:19:31

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!