【问题标题】:MVC contraint for anything that is only numeric任何只有数字的东西的 MVC 约束
【发布时间】:2010-09-23 17:19:30
【问题描述】:

我需要关于约束的帮助:

Constraints = new RouteValueDictionary(new { filename = @"" })

它只能是数字(不能是字母、斜线等)。

【问题讨论】:

    标签: asp.net-mvc routes


    【解决方案1】:

    我不确定我是否理解了这个问题,但据我所知,您可以简单地在 Constraints 字典中提供正则表达式。

    我认为MSDN refguide 中甚至还有一个例子:

    reportRoute.Constraints = new RouteValueDictionary { 
      { "locale", "[a-z]{2}-[a-z]{2}" }, 
      { "year", @"\d{4}" } };
    

    基于此,我认为你必须写什么:

    Constraints = new RouteValueDictionary(new { filename = @"\d+" })
    

    【讨论】:

    • 我认为你是对的,但你可能应该使用 \d+ 而不是 \d* - * 不允许使用 + 至少需要一个字符的字符,这可能是本意。
    • 你是对的。我不想进入正则表达式的细节,但 \d+ 绝对比 \d* 更具防御性。我已经改了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-09
    • 1970-01-01
    • 2023-03-18
    • 2011-10-21
    • 1970-01-01
    相关资源
    最近更新 更多