Skip to content

Route Constraints

mccalltd edited this page Sep 26, 2012 · 19 revisions

Thanks to the wonderful inspiration of Xavier Poinas, AttributeRouting has a completely pluggable inline constraint system.

Here are some examples of what you can do:

[GET("LengthRange/{x:length(2, 10)}")]
[GET("Range/{x:range(1, 10)}")]

As you can see, constraints take the form:


Out of the box support is available for the following:

TypeOf: int, long, float, double, decimal, bool, guid, datetime.
Strings: alpha, length(length), length(min, max), minlength(min), maxlength(max).
Numbers: min(min), max(max), range(range).
Regex: regex(pattern). 

You can chain constraints, effectively and’ing them, and you can constrain while also specifying optional params and default values:



To add your own inline constraint, just build a constraint derived from IRouteConstraint and register your constraint when configuring your routes:

RouteTable.Routes.MapAttributeRoutes(x =>
    x.InlineRouteConstraints.Add("custom", typeof(MyCustomConstraint));



Support for Enums

There is a generic attribute EnumRouteConstraint, which allows you to register your own enum constraints via the extensibility method described above.

RouteTable.Routes.MapAttributeRoutes(x =>
    x.InlineRouteConstraints.Add("color", typeof(EnumRouteConstraint<Color>));



NOTE: You can also configure route constraints against URL parameters globally when configuring your routes during application startup. More on that in the configuration wiki page.

You can’t perform that action at this time.