How to set Route Constraints ? | ASP.Net MVC Interview Question

, ,
  • It allows you to restrict the parameters in the route template are matched
  • The syntax is {parameter:constraint}

     PetController.cs

     public class PetController : Controller
      {
        // eg: /Pet/8
        [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

Route Constraints





The following diagram shows the constraints that are supported

constraints list