MSDN Documentation

Microsoft Developer Network

ASP.NET Routing Fundamentals

Understanding how your application handles incoming requests.

Understanding ASP.NET Routing

ASP.NET Routing is a powerful feature that allows you to define custom URLs for your web applications. Instead of relying on physical file paths, routing enables you to map incoming request URLs to specific handlers (like controller actions in MVC or signal handlers in Web Forms).

What is Routing?

At its core, routing is a mechanism for matching a URL request to a route definition. A route definition consists of a URL pattern and a handler that will process the request when the pattern matches. This provides greater flexibility in designing your application's URL structure, making it more user-friendly, search engine-friendly, and maintainable.

Key Concepts

How Routing Works

When a request arrives at your ASP.NET application, the routing engine iterates through the registered routes in the route table. It attempts to match the incoming URL against the URL pattern of each route. The first route that successfully matches the URL is selected.

Once a route is matched, the parameters from the URL are extracted. These parameters are then used to determine which handler should execute. For example, in an MVC application, parameters like {controller} and {action} are used to select the appropriate controller and action method.

Defining Routes

Routes are typically defined in the App_Start folder within a file like RouteConfig.cs. Here's a common example of defining a default route:


using System.Web.Mvc;
using System.Web.Routing;

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 }
        );
    }
}
            

URL Pattern Breakdown

The defaults object provides fallback values. If no controller is specified in the URL, it defaults to "Home". If no action is specified, it defaults to "Index". The id parameter is marked as UrlParameter.Optional, meaning it can be omitted entirely.

Benefits of Using Routing

Further Reading

Explore more advanced routing features: