Route constraints let you restrict how the parameters in the route template are matched. The general syntax is {parameter:constraint}. For example:
// eg: /users/5
[Route(“users/{id:int}”]
public ActionResult GetUserById(int id) { … }
// eg: users/ken
[Route(“users/{name}”]
public ActionResult GetUserByName(string name) { … }
Here, the first route will only be selected if the “id” segment of the URI is an integer. Otherwise, the second route will be chosen.
Const | Description (Matches:) | Example |
---|---|---|
alpha | Uppercase or lowercase Latin alphabet characters (a-z, A-Z) | {x:alpha} |
bool | Boolean value. | {x:bool} |
datetime | DateTime value. | {x:datetime} |
decimal | Decimal value. | {x:decimal} |
double | 64-bit floating-point value. | {x:double} |
float | 32-bit floating-point value. | {x:float} |
guid | GUID value. | {x:guid} |
int | 32-bit integer value. | {x:int} |
length | String with the specified length or within a specified range of lengths. | {x:length(6)} {x:length(1,20)} |
long | 64-bit integer value. | {x:long} |
max | Integer with a maximum value. | {x:max(10)} |
maxlength | String with a maximum length. | {x:maxlength(10)} |
min | Integer with a minimum value. | {x:min(10)} |
minlength | String with a minimum length. | {x:minlength(10)} |
range | Integer within a range of values. | {x:range(10,50)} |
regex | Regular expression. | {x:regex(^\d{3}-\d{3}-\d{4}$)} |