Routing is the process of mapping URLs (Uniform Resource Locators) to specific controllers and actions in a web application. When a user visits a URL in a web application, the routing system determines which controller and action method should handle that request.
Separation of Concerns: It allows you to organize the application’s logic by associating specific URLs with different parts of the code, improving maintainability and readability.
Custom URL Patterns: Routing enables you to create clean, human-readable, and SEO-friendly URLs for your application (e.g., /products/details instead of /product?id=123).
Dynamic URL Mapping: Routing allows dynamic mapping, where the URL could include variables (e.g., /products/{id}), making the application more flexible and capable of handling a wide range of requests.
Handling HTTP Requests: It maps incoming HTTP requests (e.g., GET, POST) to the corresponding action methods in controllers.
URL Patterns: The routing system defines URL patterns or templates that determine how URLs are matched to controller actions. For example, a URL pattern might look like /products/{id}, where {id} is a placeholder for a dynamic value (e.g., product ID).
Route Configuration: In MVC applications, routing is usually configured in a routing file (e.g., RouteConfig.cs in ASP.NET MVC or routes.rb in Rails), where the developer defines the routes and specifies what actions should handle the URL patterns.
URL → Route Configuration → Controller → Action Method → View (response to user).
In an ASP.NET MVC application, it's essential to configure at least one route in the RouteConfig class. While the MVC framework automatically provides a default route, you can add as many custom routes as necessary. These routes are defined within the RegisterRoutes method of the RouteConfig class, which resides in the RouteConfig.cs file located under the App_Start folder. The default route configuration can be found in this file, but you can modify or add new routes according to your application's requirements.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace RoutingMVCDemo
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
After defining a route, it must be registered at the application level so that it becomes available when the application starts. In ASP.NET MVC, this is done using the Global.asax file, which acts as an entry point for the application.
The Global.asax file contains the MvcApplication class, which inherits from System.Web.HttpApplication. This class provides several lifecycle methods, such as Application_BeginRequest, Application_Error, Application_Start, Session_Start, and Session_End.
To ensure that all routes are loaded when the application starts, we register them inside the Application_Start method. This is done by calling RouteConfig.RegisterRoutes(RouteTable.Routes). When the application runs for the first time, this method initializes the route table with all defined routes.
If you open the Global.asax file in your ASP.NET MVC application, you will find the following registration code. This setup ensures that the routing mechanism is in place before handling any incoming requests.
Golbal.asax
namespace FirstMVCDemo
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
To gain a clear understanding of ASP.NET MVC Routing, let's start by creating a HomeController, as demonstrated below.
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
}
By default, when you create a new ASP.NET MVC 5 application, the framework follows this routing convention. However, if you want to implement a custom routing structure, you need to modify the existing routes or define new ones, which we will explore in the next article.
Here’s how routing would work with URLs:
1.URL: http://localhost:53605/