Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
335 views
in Technique[技术] by (71.8m points)

c# - pass array of an object to webapi

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...