愛(ai)上(shang)MVC3~將系統(tong)的路由設置抽象成對象吧
對于(yu)(yu)代碼(ma)開(kai)發來說,抽象至關重(zhong)要,在(zai)MVC3中提供了路由重(zhong)寫功能,你的站點可以按著某種規范去將URL重(zhong)寫,這對于(yu)(yu)MVC來說是如此的簡單(dan),呵呵。
以往的(de)MVC項目,我們(men)習慣上把(ba)這種路由(you)配(pei)置寫在(zai)global.ascx里,這事實上不是一種好習慣,因為你的(de)模塊多(duo)了(le),路由(you)規范也多(duo)了(le),由(you)這東西多(duo)了(le)這后就顯得很亂了(le),將所以不相關的(de)代(dai)碼(ma)(ma)放在(zai)一起,這本身就是一種代(dai)碼(ma)(ma)的(de)壞(huai)味道。(我覺得我有(you)必要寫一下代(dai)碼(ma)(ma)的(de)壞(huai)味道系列了(le),呵呵)
看上去確實不(bu)是很美觀,所以,我(wo)們有必要將這個東西進行抽象,如,我(wo)要建立(li)一個與用戶相(xiang)關的路(lu)由規范(fan),我(wo)可(ke)以建立(li)這樣一個類:
/// <summary> /// 用戶中心(xin)的(de)路由規范 /// </summary> public class UserCenterRouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.MapRoute( name: "UserCenter_StudyCenter", url: "{controller}/{action}/{flag}-{page}", defaults: new { controller = "StudyCenter", action = "Index", flag = 0, page = 1 }, constraints: new { controller = "StudyCenter" } ); } }
而(er)在global.ascx里,只要注冊(ce)一個它就可以了(le),代碼如(ru)下:
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); UserCenterRouteConfig.RegisterRoutes(RouteTable.Routes);//注冊用(yong)戶中(zhong)心路由(you) RegisterRoutes(RouteTable.Routes);//注冊(ce)默(mo)認路由 }
如果你有其(qi)它模(mo)塊也可以把(ba)它們獨立出來,這樣(yang)無論是看上去,還是維護上都(dou)比混在一起了的多(duo),呵(he)呵(he)。