AngularJS $http get to ASP.NET Web Api with object in parameters
Solution 1
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
.
See : http://docs.angularjs.org/api/ng/service/$http#get
Solution 2
Yes you can send data with Get method by sending them with params
option
var data ={
property1:value1,
property2:value2,
property3:value3
};
$http({ method: 'GET', url: 'api/controller/method', params: data });
and you will receive this by using [FromUri]
in your api controller method
public IEnumerable<StuffResponse> Get([FromUri]Filter filter)
{
return GetData(filter);
}
and the request url will be like this
http://localhost/api/controller/method?property1=value1&property2=value2&property3=value3
Solution 3
Solved it this way:
Angular:
$http({
url: '/myApiUrl',
method: 'GET',
params: { param1: angular.toJson(myComplexObject, false) }
})
C#:
[HttpGet]
public string Get(string param1)
{
Type1 obj = new JavaScriptSerializer().Deserialize<Type1>(param1);
...
}
Trylling
Updated on June 07, 2022Comments
-
Trylling almost 2 years
I'm trying to get filtered data from server using a filtering object I pass to the server side. I have managed to get this working with a post:
angular:
var filter: { includeDeleted: true, foo: bar }; $http({ method: 'post', url: 'api/stuff', data: filter });
web api:
public IEnumerable<StuffResponse> Post([FromBody]Filter filter) { return GetData(filter); }
But i don't want to use a post for this, I want to use a get. But this does not work:
angular
$http({ method: 'get', url: 'api/stuff', params: filter });
web api
public IEnumerable<StuffResponse> Get([FromUri]Filter filter) { return GetData(filter); }
Also tried specifying params: { filter: filter }. If i try [FromBody] or nothing, filter is null. With the FromUri i get an object at least - but with no data. Any ideas how to solve this, without creating input parameters for all filter properties?
-
Trylling about 10 yearsAs you see in the example with 'get', I am using 'params'. And I can see the filter object is translated to URL parameters in the request - but the server can't deserialize it to the Filter object
-
Ramesh Rajendran about 10 yearsFilter is a class name, So you can't do this, you can't pass class in a query string, so you need to change the class to string,int,float...
-
testpattern over 8 yearsVil's answer provides a cleaner solution imo
-
Norbert Norbertson almost 5 yearsthat's a POST. Does it work with a get? Plus it's not angular JS.