Reputation: 58494
I am trying to create a route constraint but not sure what would be the best for this. Here is the route with no constraint :
context.MapRoute(
"Accommodation_accomm_tags",
"accomm/{controller}/{action}/{tag}",
new { action = "Tags", controller = "AccommProperty" },
new { tag = @"" } //Here I would like to put a RegEx for not null match
);
What would be the best solution for this?
Upvotes: 2
Views: 4316
Reputation: 1039398
Why do you need a constraint for a not null/empty match? Normally if you define your route like this:
context.MapRoute(
"Accommodation_accomm_tags",
"accomm/{controller}/{action}/{tag}",
new { action = "Tags", controller = "AccommProperty" },
);
and tag
is not specified in the request url this route simply won't match.
And if you want a token to be optional, then:
context.MapRoute(
"Accommodation_accomm_tags",
"accomm/{controller}/{action}/{tag}",
new { action = "Tags", controller = "AccommProperty", tag = UrlParameter.Optional },
);
Constraints are used when you want to constrain the value of a given route token to some specific format.
Upvotes: 6
Reputation: 14429
At first, I tried to create a RegEx for empty string which is ^$
(which is what null would be). However, it doesn't look like route constraints can be !=
. How about matching one or more character with ^.+$
?
So:
tag = @"^.+$"
Upvotes: 2
Reputation: 61607
Could you create an IRouteConstraint
:
public class NotNullRouteConstraint : IRouteConstraint
{
public bool Match(
HttpContextBase httpContext, Route route, string parameterName,
RouteValueDictionary values, RouteDirection routeDirection)
{
return (values[parameterName] != null);
}
}
Which you can wire up:
context.MapRoute(
"Accommodation_accomm_tags",
"accomm/{controller}/{action}/{tag}",
new { action = "Tags", controller = "AccommProperty" },
new { tag = new NotNullRouteConstraint() }
);
Upvotes: 8