10

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?

2 Answers 2

9

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]" });
Sign up to request clarification or add additional context in comments.

Comments

7

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

1 Comment

Thanks, setting a default value instead of UrlParameter.Optional did the trick. Changing the regexp didn't work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.