Routes and Controllers in ASP.NET MVC

Let’s consider a url http://localhost/home/about . How does it work in an MVC application? How does it deliver a request? Yes, routing engine is responsible for this task. So, what is routing engine? The routing engine is a core part of asp.net. It’s not tied to the MVC framework. You can use the routing engine to route requests for web form, WCF Service, actually any type of resources but in MVC we use this routing engine to direct requests to our controllers.

IC263184 - Copy

The goal of the routing engine, its job is to examine a URL and figure out where to send it for processing.

Let’s examine our TMS application (according to our previous article) or any other ASP.NET MVC application. If you open global.asax file of TMS, you can see a class here derived from HttpApplication and this allow to hook into some application level events like application start. This method(application_start) magically invoked by asp.net before processing the first http request. So when your application starts, application_start will execute one time before any of your controllers start executing. Here is the sample global.asax file.

public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

RouteConfig.RegisterRoutes(RouteTable.Routes); //Responsible for routing

BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();

}
}

In Application_Start() method the following statement is responsible for routing.
RouteConfig.RegisterRoutes(RouteTable.Routes);

If you click right button on “RegisterRoutes” and go to definition it will go to the RegisterRoutes method of the RouteConfig class which is App_Start folder. Here is the RouteConfig class. I can get into the definition of this method if I just put my cursor tight here on the method and press F12.

You have noticed that this class is called from the application start method in globa.asax.cs.

public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default", //Route Name
url: "{controller}/{action}/{id}", //URL with parameters (Pattern for the route)
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } //Default route

);
}
}

So, let me introduce details of the RegisterRoutes method. Here is the code we see, here the first statement is
routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);
It means ignore route which is in this pattern. Then let’s see the following statement. It means add a new route name “Default” and routing pattern must be “{controller}/{action}/{id}” and default routing

routes.MapRoute(
name: "Default", //Route Name
url: "{controller}/{action}/{id}", //URL with parameters (Pattern for the rout)
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } //Default route
);

Defaults route means, when you don’t type any controller or action in the URL, its goes to the index action of home controller.

Let’s go to the index action of home controller and modify the index action like following.

public ActionResult Index()
{
var controller = RouteData.Values["controller"];
var action = RouteData.Values["action"];
var id = RouteData.Values["id"];

var message = string.Format("{0}::{1} {2}",controller, action,id);

ViewBag.Message = message;

return View();
}

Now if you run the application you will see in the home page – Home::Index
If you slightly modify the url like – http://localhost:25379/Home/Index/2323.
You will see home page – Home::Index 2323
Now you understand what the function of route and controller is. Happy programming !!! :)

Recommended articles:

  1. Introduction to ASP.NET MVC
  2. How to create first Application by ASP.NET MVC
  3. Uses of ViewBag and Model in ASP.NET MVC
Please share, if it is helpfulShare on FacebookShare on LinkedInTweet about this on TwitterShare on Google+Email this to someonePrint this page

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>