ASP.NET MVC 如何簡單測試 Routes
- 2009-12-20
- 18787
- 0
- ASP.NET MVC Routes 技巧
ASP.NET MVC 的一個很重要的機制 URL Rewrite 但是當規則寫一堆以後真的很難偵錯,雖然可以利用Unit Test 來做測試,但是不一定每個人都會實作測試的,因此推薦一個快速測試Routes 的工具。
假設你的 Routes規則已經寫的和下面一樣多了,這時候偵錯真是麻煩阿。
public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Root", "", new { controller = "Home", action = "Index", id = "" }); routes.MapRoute( "Admin", "{Controller}/{action}/{id}", new { controller = "Admin", action = "Index", id = "" }, new { controller = @"^Admin+" } ); routes.MapRoute( "List", "List/{category}/{Kind}", new { controller = "Post", action = "List", Category = "", Kind = "" }, new { controller = @"^Post+" } ); routes.MapRoute( "Tag", "Tag/{category}/{Kind}", new { controller = "Post", action = "Tag", Category = "", Kind = "" }, new { controller = @"^Post+" } ); routes.MapRoute( "Rss", "Post/{category}", new { controller = "Rss", action = "Index", category = "" }, new { controller = @"^Rss+" } ); routes.MapRoute( "Home", "{action}/{id}", new { controller = "Home", action = "Index", id = "" }, new { controller = @"^Home+" } ); routes.MapRoute( "Default", "{Controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" } ); }
先不要管上面的 Routes 可不可以用,反正就只是測試案例囉。
接者把「RouteDebugger」下載回來放置於專案Bin目錄下。
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); //加上下方程式就可以做測試 RouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes); RegisterRoutes(RouteTable.Routes); }
這時候你只需要讓專案運行起來你就可以看到測試畫面囉
這對於測試實在是非常方便的工具,當測試完畢後只需要把新增的Code註解掉就可以了。
http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx
回應討論