In the previous post, we saw that we could add the Route attribute for an action in a controller. Previously if when wanted to restrict to how a parameter in a route was matched we would add a constraint in the MapHttpRoute from the config.Routes in the WebApiConfig class, like so:

    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new {id = RouteParameter.Optional},
    constraints: new {id = @"\d+"}

this constraint would make sure that the id parameter is a positive integer. But now how can we do that when we are adding the route as a string in an attribute? We just specify the constraint in the template directly:

[Route("api/foo/{id:int}", Name = "Foo")]
public string Get(int id)
    return "value";


So by adding this {id:int} we have now put on a constraint on this route so that parameter matching will be restricted to matching integers only. There is a bunch of possible constraints. Here are a few:

boolMatches a Boolean value.{x:bool}
datetimeMatches a DateTime value.{x:datetime}
decimalMatches a decimal value.{x:decimal}
doubleMatches a 64-bit floating-point value.{x:double}
floatMatches a 32-bit floating-point value.{x:float}
guidMatches a GUID value.{x:guid}
intMatches a 32-bit integer value.{x:int}
lengthMatches a string with the specified length or within a specified range of lengths.{x:length(6)}
longMatches a 64-bit integer value.{x:long}
maxMatches an integer with a maximum value.{x:max(10)}
maxlengthMatches a string with a maximum length.{x:maxlength(10)}
minMatches an integer with a minimum value.{x:min(10)}
minlengthMatches a string with a minimum length.{x:minlength(10)}

(taken from a microsoft blog, they have a bunch also)


So there it is, it’s that simple to add a powerful tool in order to better control your route mapping!