How does routing work in ASP.NET?
sobes.tech AI
Answer from AI
Routing in ASP.NET maps incoming HTTP requests to executable code (handlers, such as controller methods or Razor Pages). It determines which code should be executed in response to a specific URL.
Main components and concepts:
-
Route Template: Defines the URL structure that the router should match. It can include literals and parameters.
// Example route template "{controller=Home}/{action=Index}/{id?}"- Literals (
Home,Index) are static parts of the URL. - Parameters (
controller,action,id) are variable parts of the URL enclosed in curly braces. - Optional parameters (
id?) may be present or absent in the URL.
- Literals (
-
Route Constraints: Define rules for parameter values (e.g., data type, regex).
// Example constraint on the id parameter "{controller}/{action}/{id:int}" // id must be an integer -
Default Values: Assign default values to route parameters if they are not specified in the URL.
-
Route Order: The router checks routes in the order they are added. The first matching route handles the request. More specific routes should be defined before more general ones.
-
URL Generation: Routing is also used to create URLs based on route templates and provided parameter values.
Routing in ASP.NET Core is configured in the Configure method of the Startup class (or in Program.cs).
Example of routing configuration:
// In Startup.cs or Program.cs
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ...other middleware
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute( // For MVC controllers
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages(); // For Razor Pages
// Other routes can be added here
// endpoints.MapGet("/hello", async context => await context.Response.WriteAsync("Hello World!"));
});
// ...other middleware
}
How matching occurs:
- An incoming HTTP request enters the ASP.NET Core request pipeline.
- The
UseRouting()component adds routing middleware to the pipeline. - Routing middleware analyzes the request URL.
- It iterates through registered routes in order.
- If the request URL matches a route template and satisfies constraints, the router determines the corresponding handler (e.g., controller action method).
- The found handler (Endpoint) is stored in the request context.
- The
UseEndpoints()component executes the Endpoint found by the router. For MVC, this results in executing the corresponding controller action method.
Thus, routing is a central mechanism that links URL requests to the executable code of your application.