Introduction
ASP.NET MVC uses ASP.NET routing to map incoming browser requests to controller action methods. It is a pattern-matching system for mapping incoming requests to specified MVC Controllers and Actions. If it fails to map the route for a incoming request then MVC will show a 404 error. ASP.NET Routing uses a route table. A route table is created when your web application first starts. When an MVC application first starts, the Application_Start() method is called. This method, in turn, calls the RegisterRoutes() method. The RegisterRoutes() method creates the route table and registers one or more route patterns to the route table. If we create an application using MVC 4 or MVC 5, it has a default route register in Route.config as in the following.
Global.asax File
- protected void Application_Start()
- {
- AreaRegistration.RegisterAllAreas();
- WebApiConfig.Register(GlobalConfiguration.Configuration);
- FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
- RouteConfig.RegisterRoutes(RouteTable.Routes);
- BundleConfig.RegisterBundles(BundleTable.Bundles);
- }
- public static void RegisterRoutes(RouteCollection routes)
- {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
- routes.MapRoute(
- name: "Default",
- url: "{controller}/{action}/{id}",
- defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
- );
- }
- Controller Name
- Action Method Name
- Parameter that is passed to the action method
| Route | Controller | Action | id |
| http://<ApplicationDomain>/ | HomeController | Index | Null |
| http://<ApplicationDomain>/Home/ | HomeController | Index | Null |
| http://<ApplicationDomain>/Home/index | HomeController | Index | Null |
| http://<ApplicationDomain>/Home/index/10 | HomeController | Index | 10 |
| http://<ApplicationDomain>/Home/index?id=10 | HomeController | Index | 10 |
We can also tell the framework to ignore some kinds of requests using routes.IgnoreRoute(). Suppose we don’t want MVC to serve the following request:
http://<ApplicationDomain>/Home/
http://<ApplicationDomain>/Home/index
http://<ApplicationDomain>/Home/index/10
For this we need to ignore that route with routes.IgnoreRoute().
- public static void RegisterRoutes(RouteCollection routes)
- {
- routes.IgnoreRoute("Home/*pathInfo}");
- routes.MapRoute(
- name: "Default",
- url: "{controller}/{action}/{id}",
- defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
- );
- }
Now try the entire URL listed in the above table. Only first would be served by the Server and we would get 404 for the other requests.
Adding Custom Route and Constraints
Now to test the Route constraint I have added a new controller as Department with action as Details.
- public ActionResult Details(int DepartmentID)
- {
- return Content("received the DepartmentID as : "+ Convert.ToString(DepartmentID));
- }
- public static void RegisterRoutes(RouteCollection routes)
- {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
- routes.MapRoute(
- name: " Department",
- url: "Department/{DepartmentID}",
- defaults: new { controller = "Department", action = "Details"}
- );
- routes.MapRoute(
- name: "Default",
- url: "{controller}/{action}/{id}",
- defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
- );
- }
Please note we should register a specific route before general route. Whenever the application receives a request the framework matches it with the fist register route in the routing table and if it is ok then directs the request to the corresponding controller and action else tries with the next route in the routing table and so on. If no route matches the incoming request then the server issues a 404 to the client.
Now if you hit http://localhost:[Port]/Department/[int value] then you would get output as in the following.
If you try to pass a string then you would get the following error. As DepartmentID is expected as Integer.
When adding the route we can also define the constraints to the route. We can add constraints to a route using:
- Regular expressions
- An object that implements IRouteConstraint interface
- routes.MapRoute(
- name: "Department",
- url: "Department/{DepartmentID}",
- defaults: new { controller = "Department", action = "Details" },
- constraints: new { DepartmentID=@"\d+"}
- );
Now again hit both URLs. First run it as-is. But the output for the second URL would change to 404 errors since MVC can’t find the matching route in the Route table.
Please note that it is very possible to add a RegEx constraint to any part of the Route i.d. Controller or Action or Parameter.
We can also create a route using IRouteConstraint. It is a member of System.Web.Routing and has one method with the signature as:
- public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
Suppose we need to restrict our user to enter a DepartmentID only in the certain range, say it should be between 20 and 30.
To do that we need to create a class that implements IRouteConstraint as in the following.
- public class MyConstraint :IRouteConstraint
- {
- public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDir ection)
- {
- int id=0;
- int.TryParse(values[parameterName].ToString(), out id);
- if (20 <= id && id <= 30)
- return true;
- else
- return false;
- }
- }
- routes.MapRoute(
- name: "Department",
- url: "Department/{DepartmentID}",
- defaults: new { controller = "Department", action = "Details" },
- constraints: new { DepartmentID=new MyConstraint()}
- );
Now test the constraint and see the output.

Bruno PétersonPosted Apr 25, 2015, 10:41 AM
I needed it, thanks for sharing it.
Santhakumar MunuswamyPosted Mar 16, 2015, 1:59 PM
Very nice
Tom MohanPosted Mar 16, 2015, 12:03 PM
useful
Humayun Kabir MamunPosted Mar 16, 2015, 7:54 AM
Nice...
Antoine LOIZEAUPosted Mar 16, 2015, 7:22 AM
Great and it's simple to apply this code :)
Rahul Kumar SaxenaPosted Mar 16, 2015, 2:09 AM
Nice Work..