Isaac.

Understanding Attribute Routing in ASP.NET Core

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.

What is Attribute Routing?

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.

A Basic Example

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.

Route Parameters

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

Multiple Routes

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.

💡 Pro Tips for Attribute Routing

  • Use [Route("api/[controller]")] at the controller level and [HttpGet], [HttpPost], etc. at the method level for clarity.
  • Make use of [HttpGet("{id:int}")]to restrict route parameters to integers.
  • Keep routes consistent and RESTful (e.g., /products/{id} instead of custom verbs like /getProduct).
  • Use [Route("[action]")] to automatically use the method name as the route if you want quick prototypes.

Advantages of Attribute Routing

  • Routes are defined closer to the code they affect, improving readability.
  • Provides more control and flexibility compared to conventional routing.
  • Supports RESTful APIs with clean and descriptive endpoints.
  • Easier maintenance and debugging since routes are explicit.

Conclusion

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.