MVC Routing Basics

Routing is a fundamental aspect of any ASP .NET MVC project. ASP .NET MVC projects are already configured for basic routing needs. Routing is what drives the application and defines the structure of the urls. The routes that you define map directly to controllers and actions that carry out the behavior of your website. Any actions that the user initiates on the UI will be routed to a specific action on a controller.  

So what defines a route? Basically its just an entry in the RouteTable’s RouteCollection that is defined in the System.Web.Routing namespace. The RouteCollection in this table stores the URL definitions that handle the navtigation for the website. When the application starts, the routes you define are added to the RouteCollection with a call to MapRoute function. Here is your default route:

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

This default route allows you to add a contoller with any name and and an Index action with an optional id parameter. This can be satisfiy a number of basic needs. A home page and and simple details pages that passes an id paremeter. 

For example, let’s say I want a page to show product details. I’ll need to pass it a product id to I will create this action:

public ActionResult Product(int? id)

This URL that would map directly to that action. 

/Home/Product/1

Now let’s say that I really want the URL to look like this:

/Product/1

How do I do that? Well basically, now you need to start moving past the default route that visual studio creates and define route of your own. Here is how to do just that. Before the default route, add this route entry:

  routes.MapRoute(       "Product_Route",       "Product/{id}",          new { controller = "Home", action = "Product" },         new { id = @"d+" }   );

The names need to be unique so I named this route “Product_Route”. Notice that the URL no longer accepts any controller or any action. That means any URL that starts with “/Product” will route to this specific controller action. It also accepts an id paremeter, but notice I’ve added a contraint that specifics it must be an integer. 

So now you can see that the default route is wide open for a reason. It’s meant to accept a wide variety of routes to get you started. When you start to design your website or web application, don’t be surprised if you start define more specific routes as the early stages of the process.