When to use Attribute Routing?

The convention-based routing is complex to support certain URI patterns that are common in RESTful APIs. But by using attribute routing you can define these URI patterns very easily.
For example, resources often contain child resources like Clients have orders, movies have actors, books have authors and so on. It’s natural to create URIs that reflects these relations like as: /clients/1/orders
This type of URI is difficult to create using convention-based routing. Although it can be done, the results don’t scale well if you have many controllers or resource types.
With attribute routing, it’s pretty much easy to define a route for this URI. You simply add an attribute to the controller action as:

[Route("clients/{clientId}/orders")]
public IEnumerable < Order > GetOrdersByClient(int clientId) {
    //TO DO
}

 

Tagged , . Bookmark the permalink.

Leave a Reply