What is Attribute Routing in ASP.NET Web API 2.0?

Technology CommunityCategory: ASP.NET Web APIWhat is Attribute Routing in ASP.NET Web API 2.0?
VietMX Staff asked 3 years ago

ASP.NET Web API v2 now support Attribute Routing along with convention-based approach. In convention-based routes, the route templates are already defined as follows:

Config.Routes.MapHttpRoute(
  name: "DefaultApi",
  routeTemplate: "api/{Controller}/{id}",
  defaults: new { id = RouteParameter.Optional }
);

So, any incoming request is matched against already defined routeTemplate and further routed to matched controller action. But it’s really hard to support certain URI patterns using conventional routing approach like nested routes on same controller. For example, authors have books or customers have ordersstudents have courses etc.

Such patterns can be defined using attribute routing i.e. adding an attribute to controller action as follows:

[Route("books/{bookId}/authors")]
public IEnumerable<Author> GetAuthorsByBook(int bookId) { ..... }