AngularJS $ http get in ASP.NET Web Api with object in parameters

I am trying to get filtered data from a server using a filtering object that I pass to the server. I managed to get this working with the message:

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 do not want to use the message for this, I want to use 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);
}

We also tried to specify the parameters: {filter: filter}. If I try [FromBody] or nothing, the filter will be null. With FromUri I get an object at least - but without data. Any ideas how to solve this without creating input parameters for all filter properties?

+4
source share
4 answers

A HTTP GET . , . , angular.http params.

: http://docs.angularjs.org/api/ng/service/ $http # get

+2

, , params

var data ={
  property1:value1,
  property2:value2,
  property3:value3
};

$http({ method: 'GET', url: 'api/controller/method', params: data });

, [FromUri] api

public IEnumerable<StuffResponse> Get([FromUri]Filter filter)
{
    return GetData(filter);
}

URL- :

http://localhost/api/controller/method?property1=value1&property2=value2&property3=value3
+5

:

Angular:

$http({
       url: '/myApiUrl',
       method: 'GET',
       params: { param1: angular.toJson(myComplexObject, false) }
      })

#:

[HttpGet]
public string Get(string param1)
{
     Type1 obj = new JavaScriptSerializer().Deserialize<Type1>(param1);
     ...
}
+3

.

Script

//1.
var order = {
     CustomerName: 'MS' };
//2.
var itemDetails = [
     { ItemName: 'Desktop', Quantity: 10, UnitPrice: 45000 },
     { ItemName: 'Laptop', Quantity: 30, UnitPrice: 80000 },
     { ItemName: 'Router', Quantity: 50, UnitPrice: 5000 }
];
//3.
$.ajax({
     url: 'http://localhost:32261/api/HotelBooking/List',
     type: 'POST',
     data: {order: order,itemDetails: itemDetails},
     ContentType: 'application/json;utf-8',
     datatype: 'json'
    }).done(function (resp) {
        alert("Successful " + resp);
    }).error(function (err) {
        alert("Error " + err.status);});

API

[Route("api/HotelBooking/List")]
[HttpPost]
public IHttpActionResult PostList(JObject objData)
{  List<ItemDetails > lstItemDetails = new List<ItemDetails >();
   dynamic jsonData = objData;
   JObject orderJson = jsonData.itemDetails;
   return Ok();}
0

Source: https://habr.com/ru/post/1529377/


All Articles