ASP.NET Core Routing

This document provides a comprehensive overview of routing in ASP.NET Core, explaining how requests are mapped to specific actions in your application.

What is Routing?

Routing is the process of determining how an incoming HTTP request is handled by your web application. In ASP.NET Core, routing is a key component that matches incoming request URIs to specific endpoints. This process is primarily handled by the routing middleware.

Routing Concepts

Endpoint Routing

ASP.NET Core uses a convention-based and attribute-based routing system. Endpoint routing is the default and recommended approach.

Convention-based Routing

This is the traditional way of defining routes, typically configured in the Startup.cs (or Program.cs in .NET 6+) file. You define a default route template that applies to your entire application.

// In Startup.cs (Configure method) or Program.cs
            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });

In this example:

Attribute-based Routing

Attribute-based routing allows you to define routes directly on your controller actions using attributes. This provides more control and can be more readable for complex routing scenarios.

using Microsoft.AspNetCore.Mvc;

            [ApiController]
            [Route("api/[controller]")]
            public class ProductsController : ControllerBase
            {
                [HttpGet] // Matches GET /api/products
                public IActionResult GetAll()
                {
                    // ...
                }

                [HttpGet("{id}")] // Matches GET /api/products/{id}
                public IActionResult GetById(int id)
                {
                    // ...
                }

                [HttpPost] // Matches POST /api/products
                public IActionResult Create([FromBody] Product product)
                {
                    // ...
                }
            }

Route Constraints

Constraints are used to restrict the values that route parameters can accept. They are defined within curly braces in the route template.

Constraint Description Example Template
int Matches an integer. /products/{id:int}
alpha Matches alphabetic characters only. /users/{username:alpha}
maxLength Matches a string with a maximum length. /search/{query:maxLength(50)}
min Matches a number greater than or equal to a specified value. /items/{count:min(1)}
guid Matches a GUID. /files/{fileId:guid}

Route Parameters and Values

Route parameters are placeholders in your route template (e.g., {id}). These parameters become available as arguments to your controller actions or as properties on the RouteData object.

Generating URLs

You can use the Url.Action() or LinkGenerator service to generate URLs dynamically, which is crucial for creating links in your views and for API responses.

// In a Razor view
            <a asp-controller="Products" asp-action="Details" asp-route-id="123">View Product 123</a>

            // In a controller
            public IActionResult GetProductLink()
            {
                var url = Url.Action("Details", "Products", new { id = 456 });
                return Ok(url); // Returns a URL like "/Products/Details/456"
            }

Important Note on Order

The order in which you configure routes matters. The routing middleware processes routes in the order they are defined. More specific routes should typically be placed before more general routes.

Advanced Routing Features

Tip

When working with APIs, consider using the [Route] attribute on controllers and [HttpGet], [HttpPost], etc., on actions for clear, RESTful routing.