How do I 301 redirect /Home to root?

2019-02-27 11:57发布

问题:

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.