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

后端 未结 2 454
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-17 17:30

If I have a route like this:

routes.Add(new Route(\"{controller}/{page}\", 
    new RouteValueDictionary
    {
        { \"page\", UrlParameter.Optional }
           


        
相关标签:
2条回答
  • 2021-01-17 17:41

    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+)?" to allow nothing to match (I'm not sure about this one and can't test it atm).

    0 讨论(0)
  • 2021-01-17 17:54

    I'm using ^$| within a regex, such as: (^$|[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]" });
    
    0 讨论(0)
提交回复
热议问题