开发者

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

开发者 https://www.devze.com 2022-12-18 19:18 出处:网络
I am trying to generate a route using ASP.NET routing, but I only want it to apply if certain values are 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

精彩评论

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