I’m trying to write a route with a nullable int in it. It should be possible to go to both /profile/ but also /profile/\d+.
routes.MapRoute("ProfileDetails", "profile/{userId}",
new {controller = "Profile",
action = "Details",
userId = UrlParameter.Optional},
new {userId = @"\d+"});
As you can see, I say that userId is optional but also that it should match the regular expression \d+. This does not work and I see why.
But how would I construct a route that matches just /profile/ but also /profile/ followed by a number?
The simplest way would be to just add another route without the
userIdparameter, so you have a fallback:As far as I know, the only other way you can do this would be with a custom constraint. So your route would become:
And the custom constraint code will look like this:
I don’t know that
NullableConstraintis the best name here, but that’s up to you!