如何简化MVC3路由?

时间:2012-07-04 13:09:36

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

我有以下路线。我想我可以简化它们,但我不确定如何。有人可以给我一些建议吗?这些路线中id = ...的原因是什么?如果我的方法中没有任何id参数,那么这是做什么的吗?

context.MapRoute(
    "Admin_test",
    "Admin/Tests",
    new { controller = "Contents", action = "Tests", id = UrlParameter.Optional }
);
context.MapRoute(
    "Admin_menus",
    "Admin/Menus",
    new { controller = "Contents", action = "Menus", id = UrlParameter.Optional }
);
context.MapRoute(
    "Admin_notes",
    "Admin/Pages",
    new { controller = "Contents", action = "Pages", id = UrlParameter.Optional }
);
context.MapRoute(
    "Admin_cores",
    "Admin/Cores",
    new { controller = "Cores", action = "Cores", id = UrlParameter.Optional }
);
context.MapRoute(
    "Admin_default3",
    "Admin/References",
    new { controller = "References", action = "References", id =     UrlParameter.Optional }
);

1 个答案:

答案 0 :(得分:4)

context.MapRoute(
    "Admin_Contents",
    "Admin/{action}",
    new { controller = "Contents" },
    new { action = "^tests|menus|pages$" }
);

context.MapRoute(
    "Admin_Default",
    "Admin/{controller}",
    new { action = "Index" }
);

然后在CoresReferences控制器上使用更多RESTful操作命名约定,并使用Index作为默认操作,而不是CoresReferences

但是在第二个路由定义中,您可能还希望允许用户在URL中指定不同的操作:

context.MapRoute(
    "Admin_Default",
    "Admin/{controller}/{action}",
    new { action = "Index" }
);