WebAPI: Get Parameter Binding using [FromURI] with AngularJS $HTTP services

Standard

A HTTP GET request can’t contain data to be posted to the server. What you want is to a a query string to the request. Fortunately angular.http provides an option for it params.

2015-11-27_15-17-04

Angular Source Link for all $http options

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.

Angular Code:

$http({
         method: 'Get',
         url: 'api/BingApi/Search',
         cache: $templateCache,
         params: { query: "test" }
})

Web API Code:

[HttpGet]
public HttpResponseMessage Search(HttpRequestMessage request, [FromUri] string query)
{
    return string.IsNullOrEmpty(query) ? 
                  request.CreateResponse(HttpStatusCode.BadRequest)
                  request.CreateResponse(HttpStatusCode.OK, query); 
}
Advertisements

One thought on “WebAPI: Get Parameter Binding using [FromURI] 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