【问题标题】:ASP.NET MVC 3 Route Constraint : Regular Expression for not nullASP.NET MVC 3 路由约束:不为空的正则表达式
【发布时间】:2011-11-21 20:06:18
【问题描述】:

我正在尝试创建一个路由约束,但不确定什么是最好的。这是没有限制的路线:

context.MapRoute(
    "Accommodation_accomm_tags",
    "accomm/{controller}/{action}/{tag}",
    new { action = "Tags", controller = "AccommProperty" },
    new { tag = @"" } //Here I would like to put a RegEx for not null match
);

什么是最好的解决方案?

【问题讨论】:

    标签: asp.net asp.net-mvc regex asp.net-mvc-3 asp.net-mvc-routing


    【解决方案1】:

    你能创建一个IRouteConstraint:

    public class NotNullRouteConstraint : IRouteConstraint
    {
      public bool Match(
        HttpContextBase httpContext, Route route, string parameterName, 
        RouteValueDictionary values, RouteDirection routeDirection)
      {
        return (values[parameterName] != null);
      }
    }
    

    你可以接线:

    context.MapRoute(
      "Accommodation_accomm_tags",
      "accomm/{controller}/{action}/{tag}",
      new { action = "Tags", controller = "AccommProperty" },
      new { tag = new NotNullRouteConstraint() }
    );
    

    【讨论】:

    • 我也这么认为,如果我找不到不为空的正则表达式,这将是解决方案。谢谢!
    【解决方案2】:

    为什么你需要一个非空/空匹配的约束?通常,如果您这样定义路线:

    context.MapRoute(
        "Accommodation_accomm_tags",
        "accomm/{controller}/{action}/{tag}",
        new { action = "Tags", controller = "AccommProperty" },
    );
    

    并且 tag 没有在请求 url 中指定,这条路由根本不匹配。

    如果您希望令牌是可选的,那么:

    context.MapRoute(
        "Accommodation_accomm_tags",
        "accomm/{controller}/{action}/{tag}",
        new { action = "Tags", controller = "AccommProperty", tag = UrlParameter.Optional },
    );
    

    当您想将给定路由标记的值限制为某种特定格式时,使用约束。

    【讨论】:

    • 你又成功了。我试图记住应该有一些简单的方法,但我做不到。现在很清楚了。谢谢!
    • 如果您的操作等待字符串参数怎么办?在这种情况下,如果您将标签指定为可选参数,它将包含空值。
    【解决方案3】:

    起初,我尝试为空字符串创建一个正则表达式 ^$(这就是 null 的含义)。但是,看起来路由约束不能是!=。用^.+$匹配一个或多个字符怎么样?

    所以:

    tag = @"^.+$"
    

    【讨论】:

    • 你有两个完全相反的句子:I believe you want a RegEx for empty string...和...you want not empty string of course...
    • 好吧,他要求为 null 提供一个正则表达式,这实际上是一个空字符串,但他希望与路由约束相反。
    • 我明确指出我需要一个正则表达式来表示非空字符串。您可以在我的代码示例中将其视为注释://Here I would like to put a RegEx for not null match 我没有在任何地方要求空匹配 RegEx。很抱歉,但感谢您的努力。
    • @bzlm 它不存在。查看更新历史:stackoverflow.com/posts/7501141/revisions
    • @Cymen he he :) 谢谢,试试看。 (不过不要用力喝咖啡,不太健康。你知道我的意思 :))
    猜你喜欢
    • 2019-02-10
    • 2011-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-09
    • 2016-11-21
    相关资源
    最近更新 更多