Skip to main content

MVC - Routing



Routing is a pattern matching system which matching the incoming request URL pattern with the patterns defined in Route table.

Requests to an ASP.NET MVC-based Web application first pass through the UrlRoutingModule object, which is an HTTP module. This module parses the request and performs route selection. The UrlRoutingModule object selects the first route object that matches the current request.

In Application_start event you can register URL patterns in route table.

public class MvcApplication : System.Web.HttpApplication  
 {  
   protected void Application_Start()  
   {  
     RegisterRoutes(RouteTable.Routes);  
   }  
   public static void RegisterRoutes(RouteCollection routes)  
   {  
     routes.MapRoute(  
       "Default",                       // Route name  
       "{controller}/{action}/{id}",              // URL with parameters  
       new { controller = "Home", action = "Index", id = "" } // Parameter defaults  
     );  
   }  
 }  


Route names must be unique.

Routes are evaluated for a match to an incoming URL in order.


For global routing you can use convention based routing and register those routes in Application_Start() event.

Convention-based routing enables you to globally define the URL formats that your application accepts and how each of those formats maps to a specific action method on given controller.

routes.MapRoute(name: "Default", template: "{controller=Home}/{action=Index}/{id?}");


Attribute routing introduced in MVC 5  and it enables you to specify routing information by decorating your controllers and actions with attributes 'Route' that define your application’s routes.

public class ProductsController : Controller
{
  [Route("product/{id}")]
  public IActionResult GetProduct(int id)
  {
    ...
  }
}