Route Parameters in ASP.NET Routing

This document explains how to define and use route parameters in ASP.NET Routing. Route parameters are placeholders within a URL that allow you to capture dynamic values and pass them to your application's handlers.

What are Route Parameters?

Route parameters are segments of a URL that are not fixed. They are defined using curly braces {parameterName} within a route template. When a request matches a route containing parameters, the values from the URL are extracted and made available through the RouteData object.

Defining Routes with Parameters

You can define routes with parameters in your Global.asax file (for older ASP.NET MVC) or within your application's startup configuration (for ASP.NET Core).

Example: ASP.NET MVC

Consider the following route definition:


    routes.MapRoute(
        name: "ProductDetails",
        url: "products/{category}/{id}",
        defaults: new { controller = "Products", action = "Details" },
        constraints: new { id = @"\d+" } // Optional: Constraint for ID to be digits
    );
                

In this example:

  • {category} is a route parameter that captures the product category.
  • {id} is a route parameter that captures the product ID. The constraint ensures that only numeric IDs are matched.

A URL like /products/electronics/123 would map to the Details action of the Products controller, with category set to "electronics" and id set to "123".

Accessing Route Parameters

Route parameters can be accessed within your controller actions or route handlers.

Controller Action Example (ASP.NET MVC)


    public class ProductsController : Controller
    {
        public ActionResult Details(string category, int id)
        {
            // Use category and id to retrieve product information
            ViewBag.Category = category;
            ViewBag.ProductId = id;
            return View();
        }
    }
                

The parameters defined in the route URL are automatically mapped to the action method's parameters by name. If parameter names don't match, you can still access them via RouteData.Values.

Accessing via RouteData.Values


    public ActionResult Details()
    {
        string category = RouteData.Values["category"] as string;
        int id = Convert.ToInt32(RouteData.Values["id"]);

        // ... use category and id
        return View();
    }
                

Optional Route Parameters

You can make route parameters optional by providing default values for them in the defaults dictionary of the MapRoute method.

Example: Optional Parameter


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

In this common default route:

  • {id} is an optional parameter. If the URL does not contain an ID, the action will be called with a null or default value for id.

Tip: Parameter Naming Conventions

It's a good practice to use descriptive and consistent names for your route parameters to improve code readability and maintainability.

Parameter Constraints

Route constraints allow you to specify rules for what values a route parameter can accept. This is useful for ensuring data integrity and creating more specific routing rules.

Common constraints include:

  • \d+: Matches one or more digits.
  • [a-zA-Z]+: Matches one or more letters.
  • Custom regular expressions for more complex patterns.

Constraints are defined in the constraints parameter of MapRoute.

Route Parameters in ASP.NET Core

In ASP.NET Core, route parameters are typically defined using attribute routing or by configuring endpoints.

Attribute Routing Example (ASP.NET Core)


    [Route("api/[controller]/{id}")]
    public class ItemsController : Controller
    {
        [HttpGet]
        public IActionResult Get(int id)
        {
            // Use the 'id' parameter
            return Ok($"Item with ID: {id}");
        }
    }
                

In ASP.NET Core, parameter types are often inferred or explicitly defined, and model binding handles the assignment to action parameters.

Conclusion

Route parameters are a fundamental feature of ASP.NET Routing, enabling flexible and dynamic URL structures. By effectively using route parameters and constraints, you can create clean, SEO-friendly, and maintainable web applications.