我如何301重定向/ Home到root?

Jac*_*tti 2 asp.net-mvc asp.net-mvc-routing http-status-code-301

这是我在Global.asax中删除/ Home的路线:

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

好吧,我需要设置301重定向,因为有人链接到/ Home并且他们获得了404.

那么如何设置301呢?

我检查了路由设置的方式,并在"Home"控制器中寻找"Home"操作方法.

显然我可以添加:

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

但是,要做到这一点还有更好的方法吗?

Mel*_*igy 8

如果您想允许此URL,您可以这样做

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

但是你想要重定向,它确实最有意义,所以...

您可以做的另一件事是创建另一个控制器重定向器和一个动作主页.

public class RedirectorController : Controller
{
    public ActionResult Home()
    {
        return RedirectPermanent("~/");
    }
}
Run Code Online (Sandbox Code Playgroud)

然后将路由设置为:

routes.MapRoute("Root", "Home",
        new { controller = "Redirector", action = "Home"});
Run Code Online (Sandbox Code Playgroud)

请记住在路由顶部添加路由,以便通用路由不匹配.

更新:

您可以做的另一件事是将其添加到路线的末尾:

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

但这不是重定向.因此,可以将重定向器更改为通用...

public class RedirectorController : Controller
{
    public ActionResult Redirect(string controllerName, string actionName)
    {
        return RedirectToActionPermanent(actionName, controllerName);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后路线(现在应该在所有路线的底部)将是:

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

因此,它将尝试重定向到与/ name同名的控制器的Index操作.明显的限制是动作的名称和传递参数.你可以开始建立它.