Attribute Routing in ASP.NET Core
Learn how to use attribute routing for flexible and readable URL patterns in ASP.NET Core applications.
A Simple Analogy
Think of attribute routing like putting address labels on your mail. Instead of dropping all mail at the post office and letting them sort it, you write the exact address on each envelope. In ASP.NET Core, attribute routing lets you specify exactly which URLs map to which actions, right on the code itself.
What Is Attribute Routing?
Attribute routing is a way to define URL patterns directly on your controller actions using attributes. This gives you precise control over how requests are matched to actions, making your API or web app more flexible and readable.
Why Use Attribute Routing?
- Clarity: See the route right where the action is defined.
- Flexibility: Create custom, nested, or RESTful URL patterns easily.
- Maintainability: Change routes without editing global config files.
- Versioning: Support multiple API versions side-by-side.
How to Use Attribute Routing
1. Basic Example
[Route("api/products")]
public class ProductsController : ControllerBase
{
[HttpGet]
public IActionResult GetAll() => ...;
[HttpGet("{id}")]
public IActionResult GetById(int id) => ...;
}
2. Route Parameters
[HttpGet("{category}/items/{id}")]
public IActionResult GetItem(string category, int id) => ...;
3. Optional Parameters & Defaults
[HttpGet("{id?}")]
public IActionResult Get(int? id) => ...;
4. Constraints
[HttpGet("{id:int:min(1)}")]
public IActionResult Get(int id) => ...;
5. Route Prefixes
[Route("api/orders")]
public class OrdersController : ControllerBase
{
[HttpGet]
public IActionResult List() => ...;
}
Practical Examples
- RESTful APIs:
/api/products/42,/api/orders/2025/items/7 - Versioned APIs:
/api/v1/products,/api/v2/products - Nested resources:
/users/5/orders/12 - Custom actions:
/reports/daily,/reports/monthly
Real-World Use Cases
- E-commerce: Product, category, and order endpoints
- Social media: User profiles, posts, comments
- Healthcare: Patient records, appointments
- SaaS: Multi-tenant resource URLs
Best Practices
- Keep routes simple and predictable
- Use route constraints for validation
- Document your API endpoints
- Avoid ambiguous or overlapping routes
- Use route prefixes for grouping
- Version your API with route segments
Related Concepts to Explore
- Conventional Routing
- Route Constraints
- API Versioning
- RESTful API Design
- MVC Controllers vs. Minimal APIs
- URL Generation (UrlHelper)
- Route Templates and Tokens
- Endpoint Routing
- Middleware and Request Pipeline
- OpenAPI/Swagger Documentation
Summary
Attribute routing gives you direct, readable control over your application's URLs. By labeling each action with its route, you make your code easier to understand, maintain, and extend—whether you're building a simple web app or a complex, versioned API.