WWW Logo

When working in ASP.NET MVC and WebAPI you may run across this exception.  Consider the following controller action:

[HttpPost]
[Route("api/SomeController/SomeAction")]
public void SomeAction(int id)
{
.....
}

And a simple AngularJS ajax call to the method:

var someAction= function (id) {
var d = $q.defer();
$http.post('api/SomeController/SomeAction', id)
.success(function (data) {
d.resolve(data);
})
.error(function (data) {
d.reject(data);
});
return d.promise;
};

The ajax call can be from any client-side framework, AngularJS, jQuery, etc.  What’s important is the routing to the MVC controller action and, more specifically, how WebAPI performs the parameter binding.

By default, for value types (int, bool, string, etc) WebAPI will try and get a parameter value for a simple type from the URL.  This obviously creates an issue in this case since we are using a POST request; the parameter value will be in the body of the HTTP request and not in the URL.

In order to resolve this issue the parameter in the controller action must be decorated with the [FromBody] attribute indicating that WebAPI should look in the HTTP request body when performing the parameter binding.
The controller action would then look like this:

[HttpPost]
[Route("api/SomeController/SomeAction")]
public void SomeAction([FromBody] int id)
{
.....
}

Now the parameter binding works and the parameter value is sent to the action method just fine.

Mike Wasson has an excellent article with a lot more details here:

http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api