Home - txgz999/aspnet GitHub Wiki

Attribute Routing in WebApi

The following articles explains attribute routing well

We often use the RoutePrefix attribute at the controller level with Route attribute at the method level.

There is a convention to detect the http verb a method supports based on method name, as well as the action parameters from url query string. We need to do some extra work if not following the conversion.

// POST: api/fcm/SendMessage
[Route("sendmessage")]
public async Task<IHttpActionResult> PostMessage(

but we can have complete custom method name with a http verb attribute as follows:

// POST: api/fcm/SendMessage
[Route("sendmessage")]
[HttpPost]
public async Task<IHttpActionResult> SendMessage(

For passing parameter, we can get value from request body in one of the following ways:

  • the parameter is an instance of a business class with a FromBody attribute

Using this approach, we can send http requests with application/json as content type, and json string as request body

{ "FirstName": "John", "LastName": "Smith" }
  • the parameter is an instance of FormDataCollection, then we can fetch data from it, say form["lastName"]

Using this approach, we can send http requests with x-www-form-urlencoded as content type, and request body like the following:

FirstName=John&LastName=Smith

For details, see https://www.infoworld.com/article/3136743/how-to-pass-multiple-parameters-to-web-api-controller-methods.html.