Creating a Route Constraint in ASP.NET MVC

In this article, you will learn about how to control browser requests by specifying the route constraints with the help of regular expressions.

For that consider the default route specified in RegisterRoutes() method in RouteConfig.cs under the App_Start folder.

  1. routes.MapRoute(    
  2.     name: "Default",    
  3.     url: "{controller}/{action}/{id}",    
  4.     defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }    
  5.  );   

Now imagine that you have Details() action method in StudentController. that excepts only integer value as parameter.

So when you call this Details() method with URL that contain three segments and last segments end with integer value then it will work fine. Because route table will match any URLs with three segments. First segment in URL is corresponding to Controller name. Second segment is corresponding to action name and third segment is corresponding to an id parameter.

For example: Valid URL

Student/Details/1

Student/Details/23

Student/Details/566

  1. public class StudentController : Controller  
  2. {  
  3.    // GET: Student  
  4.    [Route("student/{id}")]  
  5.    public ActionResult Details(int id)  
  6.    {  
  7.       return View();  
  8.    }  
  9.  

But, what happens when a request comes with URL that contains three segments and third segments (id parameter) contain non integer value?

For example:

Student/Details/mannan

Unfortunately, you will get the following error. Here your intention is to match the URLs that contain three segments and third segment (id) must be an int.

 

But the value of the route parameter {id} is non integer (i.e 'mannan') and the Details() method expects an integer parameter. since value of id is not converted into an int. so the method will not execute.

In above case, you can avoid this type of error by specifying the route constraint.

Route constraint is just a condition that must be satisfied for the route to match with incoming request url.

In above case you only need the in-line integer constraint. In-line constraint is just specifying the constraint in the route template.

  1. public class StudentController : Controller  
  2. {  
  3.     // GET: Student  
  4.     [Route("student/{id:int}")]  
  5.     public ActionResult Details(int id)  
  6.     {  
  7.         return View();  
  8.     }  

List of in-line constraints.

1. {param:bool} = Boolean value

2. {param:datetime} = DateTime value

3. {param:decimal} = Decimal value

4. {param:double} = Double value

5. {param:float} = Single value

6. {param:guid} = Guid value

7. {param:int} = Int32 value

8. {param:long} = Int64 value

9. {param:minlength(n)} = string value with at least N number of characters (i.e. {param:minlength(5)} )

10. {param:maxlength(n)} = string value with less than N number of characters (i.e. {param:maxlength(5)} )

11. {param:length(n)} = string value with exactly N number of characters (i.e. {param:length(3)})

12. {param:length(minNumber,maxNumber)} = string value with minimum character and maximum character length.

13. {param:min(n)} = An Int64 value that is greater than or equal to N.(i.e. {param:min(2)})

14. {param:max(n)} = An Int64 value that is less than or equal to N.(i.e. {param:min(10)})

15. {param:range(min,max)}= An Int64 value that should be within range. (i.e. {param:range(2,5)})

16. {param:alpha} =s tring value containing only the A–Z and a–z characters

17. {param:regex (pattern)} = (i.e {param:regex (\d+)}) match only number

I hope you have enjoyed this article. If you have any questions or feedback, then please mention it in the comments section that will help me to improve my knowledge.

Ebook Download
View all
Learn
View all