2010-02-03 40 views
1

我想使用ASP.NET路由生成路由,但我只希望它應用如果某些值是數字。ASP.NET路由 - 僅在數字時才添加路由?

 // Routing for Archive Pages 
     routes.Add("Category1Archive", new Route("{CategoryOne}/{Year}/{Month}", new CategoryAndPostHandler())); 
     routes.Add("Category2Archive", new Route("{CategoryOne}/{CategoryTwo}/{Year}/{Month}", new CategoryAndPostHandler())); 

有無論如何知道{Year}和{Month}是否是數值。否則,此路由與其他路由衝突。

回答

0

好了,感謝Richard馬丁指着我朝着正確的方向前進。我最終需要的語法是:

routes.Add("Category1Archive", new Route("{CategoryOne}/{Year}/{Month}/", new CategoryAndPostHandler()) { Constraints = new RouteValueDictionary(new { Year = @"^\d+$", Month = @"^\d+$" }) }); 
routes.Add("Category2Archive", new Route("{CategoryOne}/{CategoryTwo}/{Year}/{Month}/", new CategoryAndPostHandler()) { Constraints = new RouteValueDictionary(new { Year = @"^\d+$", Month = @"^\d+$" }) }); 
3

你可以達到你想要使用constraints過濾器:

routes.MapRoute(
    "Category1Archive", 
    new Route("{CategoryOne}/{Year}/{Month}", 
      null, 
      new {Year = @"^\d+$", Month = @"^\d+$"}, 
      new CategoryAndPostHandler() 
    ) 
); 

routes.MapRoute(
    "Category2Archive", 
    new Route("{CategoryOne}/{CategoryTwo}/{Year}/{Month}", 
      null, 
      new {Year = @"^\d+$", Month = @"^\d+$"}, 
      new CategoryAndPostHandler() 
    ) 
);