What is Route?

Routes define the handler information and URL pattern. All the routes configured for an application are stored in RouteTable and it is used by route engine to handle the request.

As we all know that in classical ASP.NET, every URL was specified with .aspx extension. So the URL must match with the file in the web application. For example, if we have to request for demo.aspx than it must be localhost/demo.aspx

ASP.NET MVC introduced the concept of Routing which eliminates the need for mapping each URL with physical file present in the application. In MVC application, the request handling is done through the Controller and Action method. For example, http://localhost/home/index of MVC can be mapped to http://localhost/index.aspx for ASP.NET web forms.

How can we configure the route?

We can configure the route from the RouteConfig.cs file located at App_Start folder in the MVC application. Every MVC application registers the one route by default.

routing

routes.IgnoreRoute() is used to ignore one of the Routes. For example, two controllers are there

  • AccountController
  • HomeController

If we write routes.IgnoreRoute(“Account/”) then the request for AccountController will not be handler i.e it is ignored and 404 error page is shown.

routes.MapRoute(name,URL,defaults) is used to register the routes.

If the URL does not contain anything then the default route is rendered

Implementing Multiple Routes in MVC application

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Home",
            url: "home/{id}",
            defaults: new { controller = "Home", action = "Index"}
        );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional }
        );
    }
}

Here, if the request URL does not contain home in its request URL then only the second route is executed otherwise only home controller is only rendered.

Registering routes

After all the routes configured for our MVC application then it must register in Application_Start() event in the Global.asax file present at the root directory.

public class RoutesApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
            RouteConfig.RegisterRoutes(RouteTable.Routes);
    }
}

So when our application get started first the  Application_Start() is invoked and then it calls the RegisterRoutes table.