Routing in ASP.NET Core MVC
Routing is a fundamental concept in ASP.NET Core MVC applications. It maps incoming HTTP requests to the appropriate controller actions. This guide explores the various features and techniques for defining and managing routes.
1. Convention-Based Routing
This is the most common way to define routes. Routes are defined using route templates that map to controller and action names.
The default route template is often defined in Startup.cs
or Program.cs
:
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
This template defines:
controller
: The name of the controller (defaults to "Home").action
: The name of the action method (defaults to "Index").id?
: An optional parameter named "id".
2. Attribute Routing
Attribute routing allows you to define routes directly on your controller actions and controllers using attributes. This provides more explicit control and is often preferred for API development.
Controller-Level Routing
Define a base route for all actions within a controller:
[Route("api/[controller]")]
public class ProductsController : Controller
{
// Actions here will be prefixed with "api/Products"
}
Action-Level Routing
Define specific routes for individual action methods:
[HttpGet("details/{productId}")]
public IActionResult GetProductDetails(int productId)
{
// ...
return Ok($"Details for product {productId}");
}
[HttpPost("create")]
public IActionResult CreateProduct([FromBody] Product newProduct)
{
// ...
return CreatedAtAction(nameof(GetProductDetails), new { productId = newProduct.Id }, newProduct);
}
3. Route Constraints
Constraints allow you to restrict which requests a route can match. This is useful for ensuring parameters meet specific criteria.
Common Constraints:
int
: Matches an integer.alpha
: Matches only alphabetic characters.guid
: Matches a GUID.datetime
: Matches a date and time string.minlength
,maxlength
,length
: For string length.
Example using constraints:
[Route("articles/{year:int}/{month:alpha}/{day:int}")]
public IActionResult GetArticle(int year, string month, int day)
{
return Content($"Article on {month} {day}, {year}");
}
4. Route Parameters
Route parameters are placeholders in the route template that capture parts of the URL.
- Required Parameters:
{parameterName}
- Optional Parameters:
{parameterName?}
- Default Values:
{parameterName:default(defaultValue)}
[Route("users/{userId:int}")]
public IActionResult UserProfile(int userId) { ... }
[Route("search/{query?}")]
public IActionResult Search(string query) { ... }
[Route("products/{category=All}/{page:int=1}")]
public IActionResult ListProducts(string category, int page) { ... }
5. Route Values
Route values are key-value pairs that define the segments of a route. They are used to construct URLs and match requests.
Generating URLs with Url.Action()
and Url.RouteUrl()
:
Using Url.Action()
(requires controller and action names):
var url = Url.Action("Index", "Home", new { id = 5 });
// Example URL: /Home/Index/5
Using Url.RouteUrl()
(requires route name):
var url = Url.RouteUrl("default", new { controller = "Products", action = "Details", id = 10 });
// Example URL: /Products/Details/10
6. Route Order
The order in which routes are defined matters, especially when using both convention-based and attribute routing. ASP.NET Core processes routes in the order they are registered.
Convention-based routes are typically added first, followed by attribute-routed controllers. Be mindful of potential conflicts.
7. Route Groups (Attribute Routing)
You can group routes that share a common template prefix using the [Route]
attribute on a controller.
[Route("api/v1/[controller]")]
public class OrdersController : Controller { ... }
[Route("api/v1/[controller]")]
public class CustomersController : Controller { ... }
This results in routes like /api/v1/Orders
and /api/v1/Customers
.
8. Advanced Routing Features
- Custom Route Constraints: Implement
IRouteConstraint
for complex validation. - Route Compilers: The framework compiles route templates into efficient matching logic.
- Route Debugger: Tools like the Route Debugger middleware can help visualize and diagnose routing issues.
Summary Table of Route Templates
Template | Example URL | Matches |
---|---|---|
{controller=Home}/{action=Index}/{id?} |
/ , /Products , /Products/List , /Products/List/123 |
Default route |
api/[controller]/[action] |
/api/Products/GetAll |
Attribute route on ProductsController with [HttpGet] |
users/{userId:int} |
/users/45 |
Attribute route with integer constraint |