asp.net-web-api Attribute Routing in WebAPI

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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-api Question?