简体   繁体   English

ASP.NET MVC 2中具有约束的可选路由参数?

[英]Optional routing parameter with constraint in ASP.NET MVC 2?

If I have a route like this: 如果我有这样的路线:

routes.Add(new Route("{controller}/{page}", 
    new RouteValueDictionary
    {
        { "page", UrlParameter.Optional }
    },
    new RouteValueDictionary
    {
        { "page", @"[Pp]age\d+" }
    }, 
    new MvcRouteHandler()
));

Then the route doesn't match when {page} is missing, however if I remove the constraint it matches. 然后当{page}缺失时路线不匹配,但是如果我删除它匹配的约束。 Is this a bug or a feature? 这是一个错误还是一个功能?

I'm using ^$| 我正在使用^ $ | within a regex, such as: (^$|[Pp]age\\d+). 在正则表达式中,例如:(^ $ | [Pp] age \\ d +)。 I found this question while searching for an answer to this and figured I'd add what I found here. 我在寻找答案时发现了这个问题,并认为我会添加我在这里找到的内容。

routes.MapRoute(
  name: "News Archive",
  url: "News/{page}",
  defaults: new { controller = "news", action = "List", page= UrlParameter.Optional },
  constraints: new { page= @"^$|[0-9][0-9]" });

It's a feature: how can the constraint match if the parameter if optional? 这是一个特征:如果参数是可选的,约束如何匹配? You might either want to set the default value for "page" to "Page1" to resolve your problem, or replace your regex with "([Pp]age\\d+)?" 您可能要么将“page”的默认值设置为“Page1”以解决您的问题,或者将您的正则表达式替换为“([Pp] age \\ d +)?” to allow nothing to match (I'm not sure about this one and can't test it atm). 什么都不匹配(我不确定这个,不能测试它)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM