04 August, 2015

WebAPI 1: How to read [FromBody] parameters

For some reason – the small but important details are oftentimes difficult to recover and you are forced to resort to Googles search engine for a solution.

I have a WebAPI (version 1) method decorated with [FromBody] indicating that the WebAPI framework shall locate the ticketValue in the body of the request instead of from the URI which is the default when presented with simple types (such as string or int or…).

[POST("eticket/{version:int}")]
[
AllowAnonymous]
public void ETicket([FromBody] string ticketValue, int version)
{
//implementation omitted...
}

To my great surprise sending in the below HTTP POST request from Fiddler resulted in ticketValue being null.
The strange syntax in the body (=testValue) could also seem wrong to the first time eye, but as the WebAPI allows for only one body value, this is the syntax. I would have thought you should send in a syntax like: ticketValue=testValue, but this will not work.


image



 What I learned was:
The WebAPI uses the content-type of the incoming request to determine which media-formatter it uses to retrieve the values from the request. So the request needs to have this specified in the Request header as Content-Type: application/x-www-form-urlencoded (see below).
The below works and the WebAPI method (server side) is invoked populated from the Request when called.image

No comments:

InRiver: Not loading your extensions?

(You really need to in the loop to appreciate the issue this post addresses). Man, I've been fighting this problem for hours before I ...