Introduction
When you request any page into MVC Application, it will go through the Routing Architecture. Your Routing system will decide your URL pattern. The default routing algorithm is like {controller}/ {action}/ {id}
patterns. But it can be possible to change that pattern using Custom Routes.
In this article, we will show how to Create Custom Routes, Debugging Routes and Router Constraints.
Using Default Route
You can configure Route into the Global.aspx's Application Start Event. When you are creating an MVC application, it will already define Default route. Default route can be configured using the following code:
routes.MapRoute(
“Default”, “{controller}/{action}/{id}” , new { controller = “Home”, action = “Index”, id = ““} );
Custom Routes
It is possible to develop an MVC application without creating a Custom Route. But sometimes, there is a situation to change the pattern of URL in which it makes sense to create Custom Routes.
Now, we take a simple example of the custom routes. Imagine that you want to create a blog application and you want to route a request look like: /Archive/12-25-2010.
The first step is to create an empty MVC application. And Add Controller File named BlogController.cs and Add Actions named Archive and insert that code will look like below:
public class BlogController : Controller
{
public string Archive(DateTime? entryDate)
{
return "You wants Blog Entry on Date:=" + entryDate.ToString();
}
public ActionResult Insert()
{
ViewData["Message"] = "Call From the Insert Action When Get Http Occurs";
return View();
}
}
Now go the Global.asax file and add the following code into the Register Routes method.
routes.MapRoute(
"BlogWithoutConstraint",
"Archive/{entrydate}",
new { Controller = "Blog", action = "Archive", });
This code used to add Custom routes and it will match the URL like, Archive/12-25-2010.
Route Constraints
When you create a Custom Route, you can also include route constraints. These constraints are used to restrict the requests to match routes. There are three basic types of constraints:
- Regular Expression Constraints
HttpMethod
Constraints
CatchAll
Values
Regular Expression Constraints
You can use regular expression constraints to check the pattern of the Route and prevent invalid requests. Regular expression is used to check any pattern like Currency, Date, time, etc.
In the Above BlogArchive Example, Url likes Archive/12-25-2010 and Archive/mybirthday.
It will allow. Now we have to prevent parameter which is not a date. So it is possible using regular expression constraints. For that, add the following code into Global.aspx file Register Route method.
routes.MapRoute(
"Blog",
"Archive/{entrydate}",
new { Controller = "Blog", action = "Archive" },
new { entryDate = @"\d{2}-\d{2}-\d{4}" });
The above code matches the entry date must match pattern of two decimals followed by dash followed by two decimals followed by dash followed by four decimals.
HTTP Method Constraints
You can match route with any type of the HTTP operation like POST
, GET
, etc. you want to prevent user to access particular URL when GET
operation occurs but not POST
operation occurs. You can also used AcceptVerbs
instead of HttpMethod
constraints.
For example, BlogArchive example inserts Action
only executes when HTTP GET
Operation performs. For that, you have to add the following code into Global.asax file Register Route method.
routes.MapRoute(
"HttpMethodConstraintRoute",
"Blog/Insert",
new { Controller = "Blog", action = "Insert" },
new { method = new HttpMethodConstraint("GET") });
Catch All Routes
Generally, your URL must match with number of segments, but you want to match your URL, regardless of the number of the segments for that, we have to create Catch-All Parameter. Now take a simple example of the Catch All Routes for that add one controller named CatchAllController
and add the following code into the controller.
public class CatchAllController : Controller
{
public string Index(string AllValues)
{
string[] PassedValue = AllValues.Split('/');
return "You are Passing Values:" + String.Join(",", PassedValue);
}
}
Now to catch all parameters, add the following code into the global.asax file’s register route method.
routes.MapRoute(
"CatchAllRoute",
"CatchAll/{*AllValues}",
new { Controller = "CatchAll", action = "Index" });
Now it will match the following URL like, CatchAll/index/1/2/3/4/5/6/7 and CatchAll/a/b/c/d/e/f/g/h/.
A catch-all parameter must appear as the last parameter. Think of a catch-all parameter as a parameter array.
Debugging Routes
After creating Custom Routes, you have to check whether your routes work perfectly with your given URL or not. For that, you have to debug your routes. To Debug Routes, you have to download one DLL from the http://code.haacked.com/mvc-1.0/RouteDebug-Binary.zip and add a reference into your MVC Application.
Now debug route you have to write the following line of the code into the Global.asax Application Start Event.
RouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes);
And run your application. You will see the below screen in your browser:
You can see all the custom routes into All Routes Table and it will show that your browser URL matches with which Routes. If it will match any Routes, it will show true
into the Match Current Request Routes, otherwise it will show false
. You can check with another URL, for that you have to write URL into the Address Bar.
Now write URL like, CatchAll/1/2/3/4/5/6/. It will match with the Catchall CustomRoutes
.
In this way, you can check with other Routes too. It is possible that your URL matches with more than one Route, at that time the first match Routes Executes.
Conclusion
The goal of this article is to demonstrate the flexibility of the routing system provided by ASP.NET MVC. Hope this helps!
History
- 13th December, 2011: Initial post