【问题标题】:ASP.NET Routing - Adding a route only if numeric?ASP.NET 路由 - 仅在数字时添加路由?
【发布时间】:2010-02-03 14:51:19
【问题描述】:

我正在尝试使用 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} 是否是数值。否则此路由与其他路由冲突。

【问题讨论】:

    标签: c# asp.net routing


    【解决方案1】:

    你可以使用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()
        )
     );
    

    【讨论】:

      【解决方案2】:

      Richard 是对的,但我想补充:

      13 Asp.Net MVC Extensibility Points

      IRouteConstraint

      【讨论】:

        【解决方案3】:

        好的,感谢 Richard 和 Martin 为我指明了正确的方向。我最终需要的语法是:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-03-09
          • 1970-01-01
          • 2017-09-21
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多