2010-02-03 44 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() 
    ) 
);