This version is based on the work of Tim McCall, found at https://github.com/mccalltd/AttributeRouting
It brings a richer syntax that you can use in your route URL to specify constraints inline.
You can use the following syntax to constraint the parameter to be of the required type:
// Restrict the 'id' parameter to digits only
// Restrict the 'name' parameter to any string with a maximum length of 50-
[GET("my-url/{id:int}/{name:string(50)}")]
Here is the full list of built-in type restrictions:
string(max-length), bool, int, long, float, double, decimal
You can also add a regular expression constraint by using the following syntax:
// Restrict 'someParam' to letters only
[GET("my-url/{someParam:regex(^[a-zA-Z]+$)}")
You can easily add your own type of constraints. For example, here's how to create a constraint for even numbers:
-
Create a new class that implements
IRouteConstraint
:public class EvenRouteConstraint : IRouteConstraint { public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { var value = values[parameterName]; if (value == null) return true; int intValue; if (!int.TryParse(value.ToString(), out intValue)) return false; return intValue % 2 == 0; } }
-
Register this constraint, somewhere in your
Application_Start
:using AttributeRouting.Constraints; ... protected void Application_Start() { RouteConstraintFactory.RegisterConstraintType("even", typeof(EvenRouteConstraint)); }
-
Use the constraint:
// Restricts 'someParam' to be an even number [GET("my-url/{someParam:even}")]
You can restrict a parameter to the values of an enum
:
-
Create an enum:
public enum Colors { Red, Green, Blue }
-
Register the new constraint type:
RouteConstraintFactory.RegisterConstraintType("color", typeof(EnumRouteConstraint<Colors>));
-
Apply the constraint to a URL parameter:
// Restrict 'someParam' to values 'red', 'green' and 'blue' [GET("my-url/{someParam:color}")]