asp.net MVC - 缩短路线,禁用旧路线

asp.net MVC - shorten route, disable old route

我有一个 asp.net MVC 5 站点。

我有很多路线 - 例如

http://example.com/places/placename
http://example.com/home/about
http://example.com/home/privacy

第一个是动态的 - 后两个仅指向家庭控制器中的关于和隐私操作。

这很好用,但是,我希望所有“/home/”URL 都指向根目录。例如

http://example.com/home/privacy

应该指向

http://example.com/privacy

我也希望旧路线不再有效(内容重复对 SEO 不利)。

前者很容易做到,但老路仍然有效。处理这个问题的优雅方法是什么?

谢谢。

您可以使用 Attribute routing 并用您想要的模式装饰这些操作方法。

public class HomeController : Controller
{
   [Route("privacy")]
   public ActionResult Privacy()
   {
      return view();
   }
   [Route("about")]
   public ActionResult About()
   {
      return view();
   }
}

为了使用属性路由,必须通过在您的 RouteConfig 中调用 MapMvcAttributeRoutes 来启用它:

routes.MapMvcAttributeRoutes();

另一种选择是指定路由定义在注册默认路由定义之前(顺序matters.So特定路由定义应该在catch-rest默认路由之前注册定义)在你的 RouteConfig(传统路由方法)

因此在 RouteConfig.cs

中的 RegisterRoutes 方法中添加特定的路由定义
//register route for about
routes.MapRoute( "about", "about",
        new { controller = "Home", action = "about" });

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

使用传统的路由方法,旧的 (youtSite/home/about) 和新的路由模式 (yourSite/about) 都可以使用。如果你只想要 yourSite/about,我建议你使用属性路由方法。

你可以使用MVC5的属性路由。要启用属性路由,请在 RouteConfig.cs

中写下一行
routes.MapMvcAttributeRoutes(); // Add this line

然后你的 Homecontroller 的 Action 方法是这样的

[Route("privacy")]
public ActionResult Privacy()
{
   return view();
}

进一步了解 MVC5 Attribute Routing