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

时间:2016-10-07 22:13:16

标签: asp.net-mvc asp.net-mvc-5 asp.net-routing

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

我有很多路线 - 例如

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

第一个是动态的 - 后两个只是指向& amp;家庭控制器中的隐私行为。

这很好,但是,我希望所有'/ home /'网址指向根。例如

http://example.com/home/privacy

应指向

http://example.com/privacy

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

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

THX。

2 个答案:

答案 0 :(得分:2)

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

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

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

routes.MapMvcAttributeRoutes();

另一种选择是在注册默认路由定义之前指定路由定义(命令很重要。在catch-rest默认路由定义之前应该注册特定路由定义)在RouteConfig中路由方法)

因此,在RegisterRoutes

中的RouteConfig.cs方法中添加特定路线定义
//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,我建议您使用属性路由方法。

答案 1 :(得分:1)

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

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

然后你的Homecontroller的Action方法就像这样

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

了解有关MVC5的更多信息Attribute Routing