How do I 301 redirect /Home to root?

℡╲_俬逩灬. 提交于 2019-12-20 02:57:21

问题


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

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

Well I need to setup a 301 redirect because someone linked to /Home and they're getting a 404.

So how do I setup the 301?

I checked the way the route was setting up and it is looking for a "Home" action method in the "Home" controller.

So obviously I could add:

public ActionResult Home() {
    Response.Status = "301 Moved Permanently";
    Response.RedirectLocation = "/";
    Response.End();
    return Redirect("~/");
}

However, there's gotta be a better way of doing this right?


回答1:


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.



来源:https://stackoverflow.com/questions/5072925/how-do-i-301-redirect-home-to-root

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