开发者

ASP.NET Routing - Adding a route only if numeric?

I am trying to generate a route using ASP.NET routing, but I only want it to apply if certain values are numeric.

        // 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()));

Is there anyway to know if {Year} and {Month} are numeric values. Otherwi开发者_如何学JAVAse this routing conflicts with other routes.


You can achieve the filter you want using 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()
    )
 );


Richard is right, but I wanted to add:

13 Asp.Net MVC Extensibility Points

IRouteConstraint


Okay, thanks to Richard and Martin for pointing me in the right direction. The syntax I ended up needing is:

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+$" }) });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜