2012-07-04 31 views
2

我有以下路線。我想我可以簡化它們,但我不知道如何。有人能給我一些建議嗎?在這些路線中,id = ...的原因是什麼?如果我的方法中沒有任何id參數,那麼這是否在做任何事情?如何簡化我的MVC3路由?

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 } 
); 

回答

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控制器多一點REST風格的動作命名約定和使用Index作爲默認的動作,而不是CoresReferences

但在第二路由定義,你可能也需要允許用戶的可能性在URL中指定不同的動作:

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

非常感謝你。我不知道有可能與|結合 – Alan2

+0

是的,這是可能的。這部分路由定義稱爲路由約束:http://www.asp.net/mvc/tutorials/controllers-and-routing/creating-a-route-constraint-cs。你可以使用內建的路由約束(正則表達式,HTTP動詞)或寫一個完全自定義的約束。 –

+0

匹配url的第一條路由被拾取並路由到正確的操作和控制器。因此,www.yoursite.com/將匹配第一條路線並帶您進入內容/測試 –