c# - Web Api Post Complex-Object with Generic List-Property, Count 0 -
i have pretty basic httpclient code comes downwards this:
var criteria = new criteria() { name = "testname" }; criteria.listproperty.add(new complexobject<int>("value", true)); httpclient.postasjsonasync("api/ctl/myaction", criteria)
the controller looks this:
[httppost] public httpresponsemessage myaction([frombody]criteria criteria) { homecoming dosomethingwithit(criteria); }
the thing is, set break point on postasjsonasync
, , criteria object has name "testname", , listproperty has 1 item "value" , true properties. should be.
but break point on controller shows criteria have count 0, while still shows criteria object's name "testname." tried this:
[httppost] public httpresponsemessage myaction(object criteria) { var jsonstring = model.tostring(); }
and jsonstring has everything, including complex property "value" , true properties.
my criteria , complexobject objects so:
public class searchcriteria { public list<complexobject> listproperty { get; set; } public string name { get; set; } } public class complexobject<t> : complexobject { public t value { get; set; } public list<t> choices { get; private set; } public complexobject<t>(string complexname, bool isrequired, list<t> choices = null) { this.complexname = complexname; this.isrequired = isrequired; this.choices = choices; } } public abstract class complexobject { public string complexname { get; protected set; } public bool isrequired { get; protected set; } }
p.s.: have tried both controllers , without [frombody].
the reply is, might expect, generic types lost when crossing http or deserialized json. in order create work, had write custom parser (deserializer) on abstract complexobject, , iterator in searchcriteria phone call parser each listproperty.
in end, elegant reply web api usage between c# projects shared model namespace(s). far more complex necessary usage amongst mvc project(s) using razor and/or angularjs.
if using generics in web api , having issues, recommendation re-evaluate part of application pretty. can either have pretty backend can pass around generics, or clean frontend require more basic backend code serialize across http.
c# json web-api
No comments:
Post a Comment