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("Alpha/{x:alpha}")]
[GET("Int/{x:int}")]
[GET("Long/{x:long}")]
[GET("Float/{x:float}")]
[GET("Double/{x:double}")]
[GET("Decimal/{x:decimal}")]
[GET("Bool/{x:bool}")]
[GET("Guid/{x:guid}")]
[GET("DateTime/{x:datetime}")]
[GET("Length/{x:length(1)}")]
[GET("MinLength/{x:minlength(10)}")]
[GET("MaxLength/{x:maxlength(10)}")]
[GET("LengthRange/{x:length(2, 10)}")]
[GET("Min/{x:min(1)}")]
[GET("Max/{x:max(10)}")]
[GET("Range/{x:range(1, 10)}")]
[GET(@"Regex/{x:regex(^Howdy$)}")]

As you can see, constraints take the form:

parameterName:constraintType(params)

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:

[GET("Compound/{state:alpha:length(2)}")] 
[GET("Optionals/{age:min(18)?}])
[GET("Defaults/{state:alpha:length(2)=MT}")]

Extensibility

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.AddRoutesFromAssemblyOf<StandardUsageController>();
    x.InlineRouteConstraints.Add("custom", typeof(MyCustomConstraint));
});

then:

[GET("Path/{id:custom}")]

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.AddRoutesFromAssemblyOf<StandardUsageController>();
    x.InlineRouteConstraints.Add("color", typeof(EnumRouteConstraint<Color>));
});

then:

[GET("Colors/{which: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.