Route Constraints can be a handy way to distinguish between similar route names, and in some cases, pre-filter out “junk” requests from actually hitting your actions and taking up resources. A route constraint can be as simple as enforcing that an ID that you expect in a URL is an integer, or as complicated as regex matching on strings.
An important thing to remember is that route constraints are not a way to “validate” input. Any server side validation you wish to occur should still happen regardless of any route constraints set up. Importantly, know that if a route constraint is not met than a 404 is returned, rather than a 400 bad request you would typically expect to see from a validation failure.
Type Constraints
Type constraints are a simple way to ensure that a parameter can be cast to a certain value type. Consider the following code :
[HttpGet("{id}")] public string Get(int id) { return "value"; }
At first glance you might assume that if you called “/api/controller/abc” that the route would not match – It would make sense since the id parameter is an integer. But infact what happens is that the route is matched and the id is bound as 0. This is where route constraints come in. Consider the following :
[HttpGet("{id:int}")] public string Get(int id) { return "value"; }
Now if the id in the URL is not able to be cast to an integer, the route is not matched.
You can do this type of constraints with int, float, decimal, double, long, guid, bool and datetime.
Size Constraints
There are two types of “size” constraints you can use in routes. The first is to do with strings and means you can set a minimum length, max length or even a range.
[HttpGet("{id:minlength(4)}")] public string Get(string id) { return "value"; }
This sets a minimum length for the string value. You can also use maxlength to limit the length.
Alternatively, you can set how many characters a string can be within a range using the length property.
[HttpGet("{id:length(2,4)}")] public string Get(string id) { return "value"; }
While that’s great for string variables, for integers you can use the min/max/range constraints in a similar fashion.
[HttpGet("{id:min(1000)}")] public string Get(int id) { return "value"; }
Regex Constraints
Regex constraints are a great way to limit a string input. By now most should know exactly what regex is so there isn’t much point doing a deep dive on how to format your regex, just throw it in as a constraint and away it goes.
[HttpGet("{id:regex(\\d-\\d)}")] public string Get(string id) { return "value"; }
It is worth noting there for whatever reason, the .NET core team added another handy “quick” way of doing alpha characters only instead of regex. There you can just use the constraint of “alpha”.
[HttpGet("{id:alpha}")] public string Get(string id) { return "value"; }