Route Constraints in Asp.Net MVC with example

Route Constraints in Asp.Net MVC with example

03 Jul 2024
Intermediate
176K Views
7 min read

Route Constraints: An Overview

In the previous article, I described routingand how to create route in your application. Now the time is how to control the behavior of a route. Route constraints are a way to put some validation around the defined route. In this MVC Tutorial, we will explore more about Route Constraints which will include creating route constraints in asp.net mvc and understanding route constraints. Consider our ASP.NET MVC Course for a better understanding of all MVC core concepts.

Creating Route Constraints

Suppose we have defined the following route in our application and you want to restrict the incoming request URL with a numeric id only. Now let's see how to do it with the help of regular expression.

routes.MapRoute(
 "Default", // Route name
 "{controller}/{action}/{id}", // Route Pattern
 new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Default values for parameters
);

Restrict to numeric ID only

routes.MapRoute(
 "Default", // Route name
 "{controller}/{action}/{id}", // Route Pattern
 new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Default values for parameters
 new { id = @"\d+" } //Restriction for id
);
 

Now for this route, the routing engine will consider only those URLs that have numeric IDs like as http://example.com/Admin/Product/1 otherwise, it will consider that the URL is not matched with this route.

Creating Route Constraint to a Set of Specific Values

Suppose you want to restrict the user for those URLs that have a controller name with an H prefix and the action name should be only Index or Contact. Now let's see how to do it with the help of regular expression.

routes.MapRoute(
 "Default", // Route name
 "{controller}/{action}/{id}", // Route Pattern
 new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Default values for parameters
 new { controller = "^H.*", action = "^Index$|^Contact$" } //Restriction for controller and action
);

Now for this route, the routing engine will consider only those URLs that have a controller name with an H prefix and the action name should be only Index or Contact.

You are a little bit confused as to why it will consider this URLs. It will also consider both these since route constraints are checked after the provided default values for controller and action. In the above route default values for controller and action are Home and Index so these two URLs will also be matched. Like this, you can restrict the user according to your needs.

Note

Always put more specific routes on the top order while defining the routes, since the routing system checks the incoming URL pattern from the top and as it gets the matched route it will consider that. It will not check further routes after the matching pattern.

Types of Route Constraints

1. IntConstraint

IntConstraint matches a 32-bit integer value.

Syntax:

{ParameterName: int}

2. BoolConstraint

BoolConstraint matches a boolean value

Syntax

{ParameterName: bool}

3. DateTimeConstraint

DateTimeConstraint matches a Date Time value.

Syntax

{ParameterName:datetime}

4. DecimalConstraint

DecimalConstraint matches a decimal value.

Syntax

{ParameterName: decimal}

5. DoubleConstraint

DoubleConstraint matches a 64-bit floating-point value.

Syntax

{ParameterName: double}

6. FloatConstraint

FloatConstraint matches a 32-bit floating-point value.

Syntax

{ParameterName: float}

7. GuidConstraint

GuidConstraint matches a GUID value.

Syntax

{ParameterName:guid}

8. LongConstraint

LongConstraint matches a 64-bit integer value.

Syntax

{ParameterName: long}

9. MaxLengthRouteConstraint

MaxLengthRouteConstraint matches a string with a maximum value.

Syntax

{ParameterName:maxlength(15)}

10. MinLengthRouteConstraint

MinLengthRouteConstraint matches a string with a minimum length.

Syntax

{ParameterName:minlength(6)}

Route Constraints with example:

public class HomeController : Controller  
{ 
 // URL: /Mvctest/1  
  [Route(“Mvctest /{ customerId:int}”)]  
   public ActionResult GetCutomerById(int customerId)  
   { 
      ViewBag.Message = "Welcome to ScholarHat!";  
        return View();  
    }  

  // URL: /Mvctest/{customerName}  
    [Route(“Mvctest /{ customerName}”)]  
   public ActionResult GetCutomerByName(string customerName)  
    {  
       ViewBag.Message = "Welcome to ScholarHat!";  
        return View();  
   }  
}      

Multiple constraints Example:


/ URL: /Mvctest/1 à Action method is not be selected  
// URL: /Mvctest/1001 à Action method is selected  
 [Route(“Mvctest /{ customerId:int:min(1000)}”)]  
 public ActionResult GetCutomerById(int customerId)  
 {  
     ViewBag.Message = "Welcome to Scholarhat!";  
     return View();  
 }      
Conclusion:
So in this article, we have learned about Route Constraints in Asp.Net MVC with examples. I hope you enjoyed learning these concepts while programming with Asp.Net. Feel free to ask any questions from your side. Your valuable feedback or comments about this article are always welcome. Level up your career in MVC with our ASP.Net Core Certification.

FAQs

To restrict the browser requests that match a particular route.

Routing is a screening process that monitors applications and determines what to do with each application

There are two types of routing for action methods: Conventional Routing. Attribute Routing.
Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
Accept cookies & close this