0

I'm trying to add number/int as constraint in route.

Source: https://msdn.microsoft.com/en-us/library/cc668201.aspx#adding_constraints_to_routes

public static void RegisterRoutes(RouteCollection routes)
{
    routes.MapPageRoute("Product",
        "{ProductName}/{ProductId}",
        "~/Product.aspx",
        false,
        new RouteValueDictionary 
            {{"ProductName", "[a-z]"},{"ProductId", @"^\d+$"}}
       );
}

This is ok: example.com/productX/1234

But it is opening Product.aspx even if {ProductId} is not number/int.

So I don't want to example.com/productY/xyz route to Product.aspx. What is wrong with that route?

Second question, {ProductName} can have letters, digits and dash(-) in it, how to change {ProductName} regular expression to target all letters, numbers, and dash(-)?

akuljana
  • 187
  • 1
  • 2
  • 17

2 Answers2

1

It appears you are using the wrong overload for setting your constraints. You are trying to set defaults rather than constraints. This should work:

routes.MapPageRoute("Product",
    "{ProductName}/{ProductId}",
    "~/Product.aspx",
    false,
    null,
    new RouteValueDictionary 
        {{"ProductName", "[a-z]"},{"ProductId", @"^\d+$"}}
);

Notice the null for the defaults parameter.

As for the ProductName constraint, you can use @"^[A-Za-z0-9\-]+$". Your final code becomes:

routes.MapPageRoute("Product",
    "{ProductName}/{ProductId}",
    "~/Product.aspx",
    false,
    null,
    new RouteValueDictionary 
        {{"ProductName", @"^[A-Za-z0-9\-]+$"},{"ProductId", @"^\d+$"}}
);
Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203
0

About your 1st question look at: https://stackoverflow.com/a/273144

And 2nd: try @"^[a-zA-Z0-9-]+$"