Month End Sale: Get Extra 10% OFF on Job-oriented Training! Offer Ending in
D
H
M
S
Get Now
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

Q1. What is route constraints in ASP.NET MVC?

To restrict the browser requests that match a particular route.

Q2. What is routing in MVC with example?

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

Q3. How many types of routing are there in MVC?

There are two types of routing for action methods: Conventional Routing. Attribute Routing.
Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
.NET Solution Architect Certification Training Jul 28 SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification Training Jul 28 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
ASP.NET Core Certification Training Jul 28 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
ASP.NET Core Project Aug 24 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this