【问题标题】:ASP.NET Webforms routing, check input typesASP.NET Webforms 路由,检查输入类型
【发布时间】:2012-09-09 17:46:35
【问题描述】:

假设我在 Global.asax 中有一个类似的路由声明:

RouteTable.Routes.MapPageRoute("Products", "products/{productno}/{color}", "~/mypage.aspx");

如何配置路由,使其仅在 {productno} 是有效 Guid 且 {color} 是整数值时拦截请求?

  • 确定网址:/products/2C764E60-1D62-4DDF-B93E-524E9DB079AC/123
  • 无效的网址:/products/xxx/123

无效的 url 将被另一个规则/路由选择或完全忽略。

【问题讨论】:

    标签: c# asp.net .net routing webforms


    【解决方案1】:

    您可以通过实现匹配规则来编写自己的RouteConstraint。例如,以下是确保路由参数是有效日期的方法:

    public class DateTimeRouteConstraint : IRouteConstraint
    {
        public bool Match(System.Web.HttpContextBase httpContext, Route route, 
            string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            DateTime dateTime;
            return DateTime.TryParse(values[parameterName] as string, out dateTime);
        }
    }
    

    然后您可以通过更改路由定义来强制执行它(这是针对 MVC 2.0):

    routes.MapRoute(
        "Edit",
        "Edit/{effectiveDate}",
        new { controller = "Edit", action = "Index" },
        new { effectiveDate = new Namespace.Mvc.DateTimeRouteConstraint() }
    );
    

    这里还有一些资源:

    1. How can I create a route constraint of type System.Guid?
    2. http://prideparrot.com/blog/archive/2012/3/creating_custom_route_constraints_in_asp_net_mvc

    【讨论】:

    【解决方案2】:

    没有创建您自己的RouteConstraint 标准路由系统支持标准语法中的RegEx 路由约束。比如:

    string guidRegex = @"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$";
    string intRegex = @"^([0-9]|[1-9][0-9]|[1-9][0-9][0-9])$";
    
    routes.MapRoute(
      "Products",
      "products/{productno}/{color}",
      new { controller = "Products", action = "Index" },
      new { productno = guidRegex, color = intRegex }
    );
    

    【讨论】:

      猜你喜欢
      • 2011-08-08
      • 2016-01-06
      • 1970-01-01
      • 1970-01-01
      • 2012-03-19
      • 1970-01-01
      • 1970-01-01
      • 2011-04-16
      • 1970-01-01
      相关资源
      最近更新 更多