views:

55

answers:

3

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. Otherwise this routing conflicts with other routes.

+2  A: 

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 Szalay
A: 

Richard is right, but I wanted to add:

13 Asp.Net MVC Extensibility Points

IRouteConstraint

Martin
A: 

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