asp.net-web-api2 Attribute Routing in ASP.NET Web API 2

30% OFF - 9th Anniversary discount on Entity Framework Extensions until December 15 with code: ZZZANNIVERSARY9

Introduction

As the name suggests, this uses attributes to route. This gives the user more control over the URI's in the WebAPI. For example, you can describe hierarchies of the resource. However, the earlier 'Conventional Routing' is fully supported. Users can have a mixture of both too.

Syntax

  • [RoutePrefix("api/books")] - for controller class
  • [Route("getById")] - for actions
  • [Route("~/api/authors/{authorId:int}/books")] - for overriding route prefix

Parameters

Parameter NameDetails
RoutePrefixattribute to the controller class. all common url prefixes in actions are clubbed here. takes string as input
Routeattribute to the controller actions. each action will have route assosciated with(not necessarily)
Route("~/api/")this overrides the Route Prefix

Remarks

Currently, Attribute Routes doesn't have Controller specific Message Handlers. As there is no way to specify Which handler to execute for which route at the time of declaration. This is possible in Conventional Routing.



Got any asp.net-web-api2 Question?