2

I have written asp.net web-api project with following api-s:

Controller Method: Uri:

GetAllItems: /api/items (works)

GetItem(int id) /api/items/id (works) and

GetListOfItem(IEnumerable<Items> items) /api/items/List of items (doesn't work)

The function is similar to this (don't care about logic)

public IHttpActionResult GetByArray(IEnumerable<Book> bks)
    {
        var returnItems = items.Select(it => it).Where(it => it.Price < bks.ElementAt(0).Price || it.Price < bks.ElementAt(1).Price);
        if (returnItems == null)
            return NotFound();
        else
        {
            return Ok(returnItems);
        }
    }

I am using postman to send requests and following requests works correct

http://localhost:50336/api/items/
http://localhost:50336/api/items/100

but not

http://localhost:50336/api/items/[{"Owner":"MySelf","Name":"C","Price":151},{"Owner":"Another","Name":"C++","Price":151}]

How should i format the last request where i have a list of items in json format in order to get it works?

user1520812
  • 81
  • 1
  • 8
  • Pass the JSON in the body of the request, not the URL.. – ColinM Feb 02 '17 at 18:01
  • [Url encode](http://stackoverflow.com/questions/15872658/standardized-way-to-serialize-json-to-query-string) the object. – Jasen Feb 02 '17 at 18:06
  • Can you illustrate it with en example? I am quite new in the web world so illustrating with an example is the best way for me to understand in this case :) – user1520812 Feb 02 '17 at 21:17

2 Answers2

7

You want to decorate your method with a HttpPostAttribute and FromBodyAttribute:

[HttpPost]
public IHttpActionResult GetByArray([FromBody]IEnumerable<Book> bks)
{
}

Then send the json as post body.


Your Postman shoud look like this:

Postman

Christian Gollhardt
  • 16,510
  • 17
  • 74
  • 111
  • Can you specify with an example how should i do it. What i want to know is how should the url command be written since the one below doesn't work My methos has now the signature according to [HttpPost] public IHttpActionResult GetByArray([FromBody]IEnumerable bks) and the command sent from postman is http://localhost:50336/api/items/[{"Owner":"MySelf","Name":"C","Price":151},{"Owner":"Another","Name":"C++","Price":151}] The url command is invalid according to the answer i get from postman logs – user1520812 Feb 02 '17 at 21:10
  • Your welcome. Feel free to accept the answer then (click on the grey hook to the left) @user1520812 – Christian Gollhardt Feb 02 '17 at 21:38
2

Specifically for

GetListOfItem(IEnumerable<Items> items) 

[FromBody] is definitely best option.

In case you are using primitive types you can do following:

GetListOfItem([FromUri] int[] itemIds)

And send request as:

/GetListOfItem?itemIds=1&itemIds=2&itemIds=3 
Eckd
  • 358
  • 1
  • 10