When you request the url yourSite/Home/Index
through a browser, the routing module will direct the request to the Index
action method of HomeController
class. How does it know to send the request to this specific class's specific method ? there comes the RouteTable.
Every application has a route table where it stores the route pattern and information about where to direct the request to. So when you create your mvc application, there is a default route already registered to the routing table. You can see that in the RouteConfig.cs
class.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("Default", "{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional });
}
You can see that the entry has a name and a template. The template is the route pattern to be checked when a request comes in. The default template has Home
as the value of the controller url segment and Index
as the value for the action segment. That means, if you are not explicitly passing a controller name and action in your request, it will use these default values. This is the reason you get the same result when you access yourSite/Home/Index
and yourSite
You might have noticed that we have a parameter called id as the last segment of our route pattern. But in the defaults, we specify that it is optional. That is the reason we did not have to specify the id value int he url we tried.
Now, go back to the Index action method in HomeController and add a parameter to that
public ActionResult Index(int id)
{
return View();
}
Now put a visual studio breakpoint in this method. Run your project and access yourSite/Home/Index/999
in your browser. The breakpoint will be hit and you should be able to see that the value 999 is now available in the id
parameter.
Creating a second Route pattern
Let's say we would like a set it up so that the same action method will be called for a different route pattern. We can do that by adding a new route definition to the route table.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// New custom route definition added
routes.MapRoute("MySpecificRoute",
"Important/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional });
//Default catch all normal route definition
routes.MapRoute("Default", "{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional });
}
The new definition i added has a pattern Important/{id}
where id is again optional. That means when you request yourSiteName\Important
or yourSiteName\Important\888
, It will be send to the Index action of HomeController.
Order of route definition registration
The order of route registration is important. You should always register the specific route patterns before generic default route.