Sunday, December 22, 2013

Attribute Routing With ASP.net MVC 5 - Route Constraints

Introduction


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
      {
        // 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

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
      {
        // eg: /Pet/8
        [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

parameter is Optional


Used Dev. Environment in Article's Source Code

  • Visual Studio 2013 Express
  • .Net Framework 4.5.1
  • ASP.net MVC 5
  • C#

Conclusion

  • You saw that how easily can configure the URI Route Constraints with Attribute Routing
  • In my next article I will show how to apply Attribute Routing with Custom Route Constraints and Areas
  • So enjoy this Awesome New Feature of ASP.net MVC 5

I hope this helps to You.Comments and feedback greatly appreciated.

If you feel it was a good article,Give me a +1.Thank You.




You Might Also Like

9 comments:

  1. thanks for the information...can yo please help me solve, what if i have two different url patterns like
    a. course/search/
    b. course//enrol

    here the controller is same i.e "course"
    but the pattern is different for different action.

    pls help me solving this.

    Thanks in advance!

    ReplyDelete
  2. sorry the patterns are not posted correctly. here i mention again

    a. course/search/[searchstring]
    b. course/[courseid]/enrol

    ReplyDelete
    Replies
    1. Hi Hari,

      Please Try as shown below :

      course/search/[searchstring] - [Route("course/search/{searchstring}")]

      course/[courseid]/enrol - [Route("course/{courseid}/enrol")]

      Check this for more info : http://sampathloku.blogspot.com/2013/11/attribute-routing-with-aspnet-mvc-5.html

      Delete
  3. thanks a lot!!

    actually i want to know how to specify it in route.config.
    can we mention two routes for same controller??
    also course id has a constraint like "cannot be null and is a alpha numeric"

    any help is appreciated!
    Thanks again

    ReplyDelete
    Replies
    1. Hi Hari,

      Ans 1 : On RouteConfig file put below line :

      routes.MapMvcAttributeRoutes();//Attribute Routing

      Ans 2 : Yes,you can if you use ASP.net MVC 5.

      Ans 3 : For that,you have to create a Custom Route.Please check this article for more info : http://www.c-sharpcorner.com/UploadFile/ff2f08/custom-route-constraints-in-Asp-Net-mvc-5/

      Delete
  4. Hi
    You done a great job.
    I request to u , please write on owin authentication with full explaination.
    Also send me some useful links.

    ReplyDelete
  5. Excellent article.

    I am looking for routing with area and attribute routing in next article.

    ReplyDelete

Thanks for your Feedback.