How to implement routing in Asp.Net MVC

This articles explains how to add routing using routetable in Asp.Net MVC.

 

Posted: January 23, 2019. | By: mustafa

In Asp.Net MVC routing is done using routes defined within RouteConfig.cs and matching the incoming request's URL with the URL's defined in the Route table. We need to define routes at the Application_Start event using RouteConfig class in Global.asax.

Defining route using RouteConfig class

public static void RegisterRoutes(RouteCollection routes)
{
 routes.MapRoute(
 "Default", // Route name
 "{controller}/{action}/{id}", // Route Pattern
 new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Default values for above defined parameters
 );
}

Registering for RouteTable at Application_Start event

protected void Application_Start()
{
 RegisterRoutes(RouteTable.Routes);
 //To:DO
}

 

When the routing engine finds a match in the route table for the incoming request's URL, it forwards the request to the appropriate controller and action. If there is no match in the route table for the incoming request it returns http 404 Not Found error.

Note: Always remember route name should be unique across the entire application. Route name cannot be duplicate.

This simple article introduces you to convention-based routing in Asp.Net MVC while we can add Attribute routing in Asp.Net MVC5, please refer to know more.


related posts

Back to top