Supakit T
2 min readOct 14, 2015

ASP.NET Web API How to retrieve simple type parameter

[FromBody] prefix attribute
We need to marked [FromBody] as a prefix of primitive type parameters because primitive types parameter’s value will be searched from body of http request.

string Post([FromBody]string value)

Please keep in mind that we can have only one parameter for each request body.

How to make a http request from clients
We also need to do something at client when making a http request.
Web API’s model binder expects to find the [FromBody] values in the POST body without a key name at all. In other words, instead of key=value, it’s looking for =value.

Request’s Content-Type
We can pass parameter from client in two ways

  1. Content-Type: application/x-www-form-urlencoded
    this way need to prefixed “=” before the value e.g. =parameter value
Fiddler client testing

For jQuery $.ajax(), There are two ways to make it works

$.post(‘api/Post’, “=” + value);

$.post(‘api/Post’, { ‘’: value });
Note: Notice that the ‘’ key value has no space between the single quotes.

For AngularJs $http

$http({ url: serverUrl, method: “POST”, data: “=” + postData })

2. Content-Type: application/json
this way needs to quote the value with double quote e.g. “parameter value”

Fiddler client testing

if parameter type is string we need JSON.stringify() to quote the parameter
otherwise just the pure value

$http({ url: serverUrl, method: “POST”, JSON.stringify(postString) })

Reference :
http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Supakit T
Supakit T

Written by Supakit T

Either Programmer Diving or Programming Diver anyway just code.

No responses yet

Write a response