Here is my route:
routes.MapRoute(null, "myaccount/monitor/{category}", // Matches
new { controller = "MyAccount", action = "Monitor", category = (string)null }
);
I would like to add a constraint so the category can only match a null or one of three params (i.e. overview, projection, history)
there are no limits in creating routes. You can create as many route as you want in your RouteConfig.
We can apply the multiple constraints to a parameter by a colon (:) separator. [Route(URLPath/{parameterName: constrain:Constrain:….})] In the preceding example, the route will only be selected if the parameter id is an integer as well as a value of id greater than 1000.
The Route Constraint in ASP.NET MVC Routing allows us to apply a regular expression to a URL segment to restrict whether the route will match the request. In simple words, we can say that the Route constraint is a way to put some validation around the defined route.
You can use UrlParameter.Optional
to allow nulls, and also use the constraints
parameter of the MapRoute
method..
routes.MapRoute(null,
"myaccount/monitor/{category}", // Matches
new { controller = "MyAccount", action = "Monitor", category = UrlParameter.Optional },
new { category = "overview|projection|history"}
);
The inline Regex Gaby posted would work. Another way to do it is to define a custom IRouteConstraint:
public class FromValuesListConstraint : IRouteConstraint
{
private List<string> _values;
public FromValuesListConstraint(params string[] values)
{
this._values = values.Select(x => x.ToLower()).ToList();
}
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
string value = values[parameterName].ToString();
if (string.IsNullOrWhiteSpace(value))
{
return _values.Contains(string.Empty);
}
return _values.Contains(value.ToLower());
}
}
Then pass in an instance of the constraint into your MapRoute call:
routes.MapRoute(null,
"myaccount/monitor/{category}", // Matches
new { controller = "MyAccount", action = "Monitor", category = UrlParameter.Optional },
new { category = new FromValuesListConstraint ("overview", "projection", "history", string.Empty) }
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With