Attribute routing in ASP.NET Core makes it easier to define clear, intuitive, and RESTful routes directly inside your controller actions. This article will walk you through what attribute routing is, how it works, and provide examples to help you use it effectively.
Attribute routing lets you define routes by decorating your controller actions with route attributes. Instead of relying solely on conventional routes defined in Program.cs, you place routing logic directly above your action methods. This results in clearer and more maintainable code.
Here’s a simple controller demonstrating attribute routing:
[ApiController]
[Route("api/[controller]")] // Base route
public class ProductsController : ControllerBase
{
[HttpGet] // GET api/products
public IActionResult GetAllProducts()
{
return Ok(new [] { "Laptop", "Phone", "Tablet" });
}
}In this example, the route becomes: /api/products. How? Notice that the controller name is ProductsController. Whatever becomes before "Controller" is used in the route. The [HttpGet] attribute above the GetAllProducts indicates that this action responds to GET requests.
You can add route parameters to make your API endpoints more flexible:
[HttpGet("{id}")] // Route parameter
public IActionResult GetProductById(int id)
{
return Ok($"You requested product with ID: {id}");
}The endpoint can now be called using: /api/products/5
Sometimes you want multiple routes pointing to the same action:
[HttpGet("all")]
[HttpGet("list")] // Multiple routes
public IActionResult GetProducts()
{
return Ok(new [] { "Laptop", "Phone", "Tablet" });
}This allows both /api/products/all and /api/products/list to return the same result.
[Route("api/[controller]")] at the controller level and [HttpGet], [HttpPost], etc. at the method level for clarity.[Route("[action]")] to automatically use the method name as the route if you want quick prototypes.Attribute routing in ASP.NET Core is a powerful way to design RESTful APIs with clear, simple, and maintainable routes. By defining routes directly on controller actions, you make your code easier to understand and your API endpoints more intuitive.