Quels sont les usages des routes ?

Mastering ASP.NET Core Routing

16/06/2025

Rating: 4.84 (1688 votes)

Understanding Routing in ASP.NET Core

Routing is a fundamental concept in web development, particularly within the ASP.NET Core framework. It's the process by which incoming HTTP requests are directed to the correct code that will handle them. Think of it as the traffic controller for your web application, ensuring that every URL request finds its designated destination. This article will delve deep into the intricacies of routing in ASP.NET Core, covering its core components, configuration methods, and best practices to help you build robust and scalable web applications.

Quels sont les éléments du code de la route ?
Votre tâche dans "Codexions" est de relier 16 éléments du code de la route en quatre groupes de quatre, chaque groupe exposant un thème commun, tel que la priorité de passage, les panneaux de signalisation, les règles de stationnement, ou les consignes de sécurité.
Table

What is a Route?

In the context of ASP.NET Core, a route is a defined pattern that matches a URL. When a request comes in, the routing system compares the request's URL against a collection of configured routes. The first route that successfully matches the URL is used to determine which code, typically a controller and an action method, should process the request. A route is generally defined by a template, which can include fixed segments, parameters, and constraints. For example, a common route template is {controller=Home}/{action=Index}/{id?}. This template specifies that the URL can be broken down into three parts: a controller name (defaulting to 'Home'), an action method name (defaulting to 'Index'), and an optional 'id' parameter.

Key Components of Routing

The routing system in ASP.NET Core is composed of several key elements that work together to direct requests:

  • Routes: These are the core definitions that map URL patterns to specific actions. Each route has a template, which can include placeholders for dynamic values like controller names, action names, and IDs.
  • Route Collection: A collection that holds all the defined routes. Routes are tested in the order they appear in this collection. The first match typically wins.
  • IRouter Interface: This interface defines the contract for objects that handle routing. Classes implementing IRouter are responsible for matching requests to routes and generating URLs. The default implementation for MVC applications is MvcRouteHandler, which identifies the appropriate controller and action.

Configuring Routes

There are two primary ways to configure routes in ASP.NET Core:

1. Convention-Based Routing (Using Templates)

This is the most common method. You define route templates in your application's startup configuration, typically in the Configure method of your Startup.cs file. This approach uses a set of rules to construct URLs and map them to controller actions.

Basic Configuration

To enable convention-based routing, you need to add MVC services and use the MVC middleware:

public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version22); } public void Configure(IApplicationBuilder app) { app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }}

The MapRoute method allows you to define a named route with a specific template. The "{controller=Home}/{action=Index}/{id?}" template is a common default, meaning if no controller is specified, it defaults to 'Home', and if no action is specified, it defaults to 'Index'. The '?' makes the 'id' parameter optional.

Quel est le synonyme de route ?
Voie publique (openbare weg), route (weg)... ÉVÉNEMENT TYPE/PROTOCOLE ■Par défaut (sur voie publique) :

Route Template Syntax

Route templates are powerful and flexible. Here's a breakdown of their syntax:

  • Placeholders: Enclosed in curly braces {}, e.g., {controller}, {action}, {id}. These capture parts of the URL.
  • Optional Parameters: Appended with a question mark ?, e.g., {id?}.
  • Default Values: Specified using an equals sign =, e.g., {action=index}. If the parameter is not present in the URL, the default value is used.
  • Fixed Values: Literal strings that must match exactly, e.g., admin/{controller}.

Constraints

You can add constraints to parameters to ensure they meet specific criteria:

  • Type Constraints:{id:int}, {name:alpha}, {date:datetime}.
  • Value Constraints:{id:min(5)}, {id:maxlength(10)}, {id:range(1,10)}.
  • Regular Expressions:{id:regex(^\d{{5}}$)} for a 5-digit ID.

Order Matters

The order in which you define your routes is crucial. The routing engine processes routes sequentially, and the first one that matches the incoming URL is used. More specific routes should generally be defined before more general ones.

Example Table of Route Templates and Matches:

Route TemplateURLMatched ControllerMatched ActionMatched ID
{controller}/{action}/{id?}Products/List/5ProductsList5
{controller}/{action}/{id?}Products/ListProductsListnull
admin/{controller}/{action}admin/Users/DetailsUsersDetailsnull
{controller}/{action=Index}/{id?}ProductsProductsIndexnull

2. Attribute Routing

Attribute routing allows you to define routes directly on your controllers and action methods using attributes. This approach offers more explicit control and can make your routing logic clearer, especially for APIs.

Applying Attributes

  • Controller Level: Use the [Route("api/[controller]")] attribute to set a base route for all actions within a controller. [controller] is a token that gets replaced by the controller's name.
  • Action Level: Use [HttpGet], [HttpPost], [HttpPut], [HttpDelete], or the general [Route("actionName")] attribute to define specific routes for individual actions.
[Route("api/[controller]")] [ApiController] public class ProductsController: ControllerBase { [HttpGet] public IActionResult GetAllProducts() { // ... } [HttpGet("{id}")] public IActionResult GetProductById(int id) { // ... } [HttpPost] public IActionResult CreateProduct([FromBody] Product product) { // ... } }

Combining Attributes

Attributes can be combined. A route defined at the controller level serves as a prefix for routes defined at the action level. You can also apply multiple route attributes to a single action to support different URL patterns.

HTTP Method Constraints

Attributes like [HttpGet], [HttpPost], etc., not only define the route but also specify the HTTP method the action will respond to. This is crucial for building RESTful APIs.

Comment utiliser plusieurs routes pour une même action ?
Il est possible d’utiliser plusieurs routes pour une même action en utilisant plusieurs attributs [Route] au même niveau. Par exemple, dans la classe PizzaOrderController, l'action Index est accessible via plusieurs routes : ['', 'Index', '/'].

Tokens and Constraints in Attributes

Similar to convention-based routing, you can use tokens like [controller] and [action], and apply constraints like {id:int:range(1,10)} directly within route attributes.

Using Multiple Routes for the Same Action

You can map multiple routes to a single action method by applying multiple [Route] attributes or by defining multiple routes in your Startup.cs file that point to the same controller and action.

Custom Route Handlers

For more advanced scenarios, you can implement your own route handler by creating a class that implements the IRouter interface. This allows you to define custom routing logic, such as conditional routing based on request headers or other factors.

Qu'est-ce qu'une route?
Dans le contexte de ce document, une voie présentant la même unité administrative (type et numéro) est appelée une route.
public class CustomRouter: IRouter { // ... implementation ... } // In Startup.cs: app.UseMvc(routes => { routes.Routes.Add(new CustomRouter(routes.DefaultHandler)); routes.MapRoute(...) });

Routing in ASP.NET Core 2.2 and Later (Endpoint Routing)

Starting with ASP.NET Core 2.2, a new routing middleware called "Endpoint Routing" was introduced. This middleware performs routing earlier in the pipeline, before the MVC middleware. This change impacts how you configure routing, especially when using custom route handlers or older routing mechanisms.

To use the older routing behaviour (which might be necessary for certain custom scenarios) with UseMvc, you might need to disable endpoint routing:

services.AddMvc(options => options.EnableEndpointRouting = false).SetCompatibilityVersion(CompatibilityVersion.Version22);

When to Use Which Method?

  • Convention-Based Routing: Ideal for traditional web applications where URLs follow a predictable pattern. It's often simpler to set up for the entire application.
  • Attribute Routing: Excellent for APIs and scenarios where you need fine-grained control over individual routes. It keeps route definitions close to the code they affect.

Common Pitfalls and Best Practices

  • Route Order: Always consider the order of your routes. Place more specific routes before general ones.
  • URL Cannibalization: Be mindful of defining routes that are too similar, which can lead to unexpected behavior.
  • Readability: Use meaningful names for your routes and keep your templates clean.
  • Consistency: Maintain a consistent routing strategy throughout your application.
  • Testing: Thoroughly test your routing by making requests with various URLs to ensure they are handled correctly.

Frequently Asked Questions (FAQ)

What is the difference between convention-based routing and attribute routing?

Convention-based routing defines routes using templates in the startup configuration, while attribute routing defines routes directly on controllers and actions using attributes.

Can I use both convention-based and attribute routing in the same application?

Yes, you can use both. Attribute routing takes precedence over convention-based routing for the actions where attributes are defined.

How do I handle optional parameters in a route?

Append a question mark (?) to the parameter in the route template, e.g., {id?}.

Quel est le synonyme de route ?
Voie publique (openbare weg), route (weg)... ÉVÉNEMENT TYPE/PROTOCOLE ■Par défaut (sur voie publique) :

What is the purpose of route constraints?

Route constraints ensure that route parameters match specific criteria (like type, length, or value range), preventing invalid URLs from being processed.

How does the order of routes affect my application?

The routing engine processes routes in the order they are defined. The first route that matches the incoming URL is used. Therefore, more specific routes should be placed before more general ones.

Conclusion

Mastering ASP.NET Core routing is essential for building well-structured and efficient web applications. By understanding the different configuration methods, route templates, attributes, and constraints, you can effectively manage how your application responds to incoming requests. Whether you opt for convention-based routing, attribute routing, or a combination of both, a clear and well-defined routing strategy is key to a successful web development project.

If you want to read more articles similar to Mastering ASP.NET Core Routing, you can visit the Automotive category.

Go up