pass array of an object to webapi

Christopher Johnson picture Christopher Johnson · Dec 20, 2012 · Viewed 11k times · Source

I have a .net mvc 4 webapi project that I'm trying to pass an array of an object to a method on my controller.

I've found some examples here on SO that talk about needing to set my object's properties with: param1=whatever&param2=bling&param3=blah.

But I don't see how I can pass in a collection using that.

Here is my method signature. Notice I've decorated the argument with the [FromUri] attribute.

public List<PhoneResult> GetPhoneNumbersByNumbers([FromUri] PhoneRequest[] id)
{
    List<PhoneResult> prs = new List<PhoneResult>();
    foreach (PhoneRequest pr in id)
    {
        prs.Add(PhoneNumberBL.GetSinglePhoneResult(pr.PhoneNumber, pr.RfiDate, pr.FinDate, pr.State));
    }
    return prs;
}

here is my simple PhoneRequest object:

public class PhoneRequest
{
    public string PhoneNumber { get; set; }
    public string RfiDate { get; set; }
    public string FinDate { get; set; }
    public string State { get; set; }
}

and here's a sample of what I'm using to pass in:

http://localhost:3610/api/phonenumber/getphonenumbersbynumbers/
   [{"PhoneNumber":"8016667777","RfiDate":"","FinDate":"2012-02-11","State":"UT"},
    {"PhoneNumber":"8018889999","RfiDate":"2012-12-01","FinDate":"","State":"UT"}]

using this comes back with "bad request"

I also tried this

http://localhost:3610/api/phonenumber/getphonenumbersbynumbers?
    id=[{"PhoneNumber":"8016667777","RfiDate":"","FinDate":"2012-02-11","State":"UT"},
        {"PhoneNumber":"8018889999","RfiDate":"2012-12-01","FinDate":"","State":"UT"}]

which does reach the method, but the array is null.

how can I pass in an array of my PhoneRequest object to my Web API method?

Answer

Maggie Ying picture Maggie Ying · Dec 20, 2012

Try passing the PhoneRequest[] from the uri in this format:

http://localhost:3610/api/phonenumber/getphonenumbersbynumbers?
    id[0][PhoneNumber]=8016667777&id[0][FinDate]=2012-02-11&id[0][State]=UT&
    id[1][PhoneNumber]=8018889999&id[1][RfiDate]=2012-12-01&id[1][State]=UT