Quantcast
Channel: Web API
Viewing all articles
Browse latest Browse all 4850

Passing complex type containing array of complex types to Web API

$
0
0

I'm trying to pass a complex object containing a collection of complex objects to an ASP.NET Web API controller action method, but there's a catch: I have to pass it either in the querystring, or (preferably) as POST with Content-Type of "application/x-www-form-urlencoded" (a standard HTML form POST).

If I pass a PhoneRequest object that contains a collection of phone numbers...

public class PhoneRequest
{
    public string[] PhoneNumbers { get; set; }
    public string State { get; set; }
}

...and I either pass the parameter as a URL encoded query string:

/api/phonenumber?id[0][State]=UT&id[0][PhoneNumbers][0]=555-1234567

...or POST it as a html form encoded (Content-Type: application/x-www-form-urlencoded) request body:

[0][State]=UT&[0][PhoneNumbers][0]=555-1234567

...then everything works great. But If I change "PhoneNumbers" from a collection of strings to a collection of a new "PhoneNumber" type...

public class PhoneRequest
{
    public PhoneNumber[] PhoneNumbers { get; set; }
    public string State { get; set; }
}
public class PhoneNumber
{
    string AreaCode { get; set; }
    string Number { get; set; }
}

...and I pass the object in what appears to me to be the logical way, given the previous result...

id[0][State]=UT&id[0][PhoneNumbers][0][AreaCode]=555&id[0][PhoneNumbers][0][Number]=1234567

...or again as a html form post body...

[0][State]=UT&[0][PhoneNumbers][0][AreaCode]=555&[0][PhoneNumbers][0][Number]=1234567

...then it still makes an attempt to bind it, and gets into my action method, but the model only contains State, and the phone number is this weird "ComplexUriAndFormObject" thing. Here's a copy-paste from my debugger Watch:

phoneRequest    {ComplexUriAndFormObject.Models.PhoneRequest[1]}
    [0] {ComplexUriAndFormObject.Models.PhoneRequest}
        PhoneNumbers    {ComplexUriAndFormObject.Models.PhoneNumber[1]}
        [0] {ComplexUriAndFormObject.Models.PhoneNumber}
            AreaCode    null
            Number  null
        State   "UT"

Is there some way to specify this object correctly using this format? Or have I exceeded the limit of what ASP.NET Web API's built in model binders are able to do?

Note: Please don't say "just use POST" or "just use JSON/XML/Whatever as your Content-Type"... If I was able to do that, I would.


Viewing all articles
Browse latest Browse all 4850

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>