This Article shows how to use the Latest ASP.net MVC 5 Attribute Routing's Route Constraints with your Application. You can read the first part of this Article here 'Attribute Routing With ASP.net MVC 5. If you want to be more familiar with ASP.NET MVC 5, you should try HostForLife.eu.

How to set Route Constraints ?
It allows you to restrict the parameters in the route template are matched
The syntax is {parameter:constraint}

PetController.cs

public class PetController : Controller
{
[Route("Pet/{petId:int}")]
public ActionResult GetSpecificPetById(int petId)
{
return View();
}
}

Key points of the above code:
- In the above example, /Pet/8 will Route to the “GetSpecificPetById” Action.
- Here the route will only be selected, if the "petId" portion of the URI is an integer.
Above Route on Browser is as below

The following diagram shows the constraints that are supported

How to apply multiple constraints to a parameter ?

You can apply multiple constraints to a parameter, separated by a colon.
Well,It's like this  [Route("Pet/{petId:int:min(1)}")]

PetController.cs

public class PetController : Controller
{
[Route("Pet/{petId:int:min(1)}")]
public ActionResult GetSpecificPetById(int petId)
{
return View();
}
}


Key points of the above code
In the above example,You can't use  /Pet/10000000000 ,because it is larger than int.MaxValue
And also you can't use /Pet/0 ,because of the min(1) constraint.

How to Specifying that a parameter is Optional ?
You can do it by Specifying that a parameter is Optional (via the '?' modifier).
This should be done after inline constraints.
Well,it's like this  [Route("Pet/{message:maxlength(4)?}")]

PetController.cs

// eg: /Pet/good
[Route("Pet/{message:maxlength(4)?}")]
public ActionResult PetMessage(string message)
{
return View();
}


Key points of the above code
In the above example, /Pet/good and /Pet will Route to the “PetMessage” Action.
The route /Pet also works hence of the Optional modifier.
But /Pet/good-bye will not route above Action , because of the maxlength(4) constraint.

Above Routes on Browser are as below