Web Api Parameter always null

[Originally Posted By]: http://stackoverflow.com/questions/14624306/web-api-parameter-always-null

$.ajax({
    url: '/api/search',
    type: 'POST',
    contentType: 'application/x-www-form-urlencoded; charset=utf-8',
    data: '=' + encodeURIComponent(request.term),
    success: function (data) {
        response(data.d);
    },
    error: function (result) {
        alert('Error');
    }
});

Basically you can have only one parameter of scalar type which is decorated with the [FromBody]attribute and your request needs to use application/x-www-form-urlencoded and the POST payload should look like this:

=somevalue

Notice that contrary to standard protocols the parameter name is missing. You are sending only the value.

You can read more about how model binding in the Web Api works in this article.

But of course this hacking around is a sick thing. You should use a view model:

public class MyViewModel
{
    public string Value { get; set; }
}

and then get rid of the [FromBody] attribute:

public IEnumerable<string> Post(MyViewModel model)
{
    return new string[] { "value1", "value2", model.Value };
}

and then use a JSON request:

$.ajax({
    url: '/api/search',
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify({ value: request.term }),
    success: function (data) {
        response(data.d);
    },
    error: function (result) {
        alert('Error');
    }
});
shareedit

whenever we are calling web api action and which take [frombody] parameter then input parameter prefix with = for example

public string GetActiveEvents([FromBody] string XMLRequestString) {
}

to call above web api action

  1. URI
  2. 2.

User-Agent: Fiddler

Content-Type: application/x-www-form-urlencoded

Host: localhost:54702

Content-Length: 936

  1. request body is =data

I hope this will give clear idea.

shareedit
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s