c# - How to Post JSON data to a Web API using HttpClient -
i have following code, takes in dynamic object (in case of type file) , using httpclient
class tries post webapi controller
, issue having controller getting null
values on [frombody]
parameter.
code
var obj = new { f = new file { description = description, file64 = convert.tobase64string(filecontent), filename = filename, versionname = versionname, mimetype = mimetype }, } var client = new httpclient(signinghandler) { baseaddress = new uri(baseurl + path) //in case v1/document/checkin/12345 }; client.defaultrequestheaders.accept.clear(); client.defaultrequestheaders.accept.add(new mediatypewithqualityheadervalue("application/json")); httpresponsemessage response; action = uri.escapeuristring(action); //obj passed this, of type file var content = new stringcontent(jsonconvert.serializeobject(obj).tostring(), encoding.utf8, "application/json"); response = client.postasync(action, content)).result; if (response.issuccessstatuscode) { var responsecontent = response.content; string responsestring = responsecontent.readasstringasync().result; return jsonconvert.deserializeobject<t>(responsestring); }
controller
[httppost] [route("v1/document/checkin/{id:int}")] public void checkin_v1(int id, [frombody] file f) { //do stuff - f has null on of properties }
model
public class file { public string filename { get; set; } public string versionname { get; set; } public string description { get; set; } public string mimetype { get; set; } public byte[] bytes { get; set;} public string file64 { get; set; } }
the model shared on both webapi
, client app.
any on why failing appreciated, been going around in circles while now.
your obj right @ start isn't needed. nesting f inside object.
var obj = new { f = new file { description = description, file64 = convert.tobase64string(filecontent), filename = filename, versionname = versionname, mimetype = mimetype }, }
change to
var f = new file { description = description, file64 = convert.tobase64string(filecontent), filename = filename, versionname = versionname, mimetype = mimetype };
then serialize f.
Comments
Post a Comment