WebAPI: Post Parameter Binding using [FromBody] with AngularJS HTTP services

Standard

Simple code example to consume asp.net WebAPI with AngularJS SPA application.

AngularJS Code:

return $http({
    method: 'POST',
    url: window.location.protocol + '//' + window.location.host + window.location.pathname + '/api/JobDetails/AddFeedback',
    data: JSON.stringify(objFeedback),
    cache: $templateCache
});

Key thing to note here is to convert your parameter content to JSON in POST request header.

WebAPI code:

[HttpPost]
public HttpResponseMessage AddFeedback(HttpRequestMessage request, [FromBody] object value)
{
    return value.ToString() != null ?
        request.CreateResponse(HttpStatusCode.OK) : request.CreateResponse(HttpStatusCode.BadRequest);
}

By default, Web API uses the following rules to bind parameters:

–  If the parameter is a “simple” type, Web API tries to get the value from the URI. Simple types include the .NET primitive types (int, bool, double, and so forth), plus TimeSpan, DateTime, Guid, decimal, and string, plus any type with a type converter that can convert from a string. (More about type converters later.)
–  For complex types, Web API tries to read the value from the message body, using a media-type formatter. This includes [FromBody], [FromUri], and [ModelBinder], or custom attributes.

Advertisements

One thought on “WebAPI: Post Parameter Binding using [FromBody] with AngularJS HTTP services

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