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

ⅰ亾dé卋堺 提交于 2019-12-01 15:20:42

问题


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. Is this a bug or a feature?


回答1:


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).




回答2:


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]" });


来源:https://stackoverflow.com/questions/3468115/optional-routing-parameter-with-constraint-in-asp-net-mvc-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!