Saturday, 15 February 2014

asp.net - How do I send an object to my Web API? -



asp.net - How do I send an object to my Web API? -

i've built first asp.net web api. i'm trying send object api not sure how it.

here's code far:

employee employee = new employee(); employee.id = 1234; employee.firstname = "john"; employee.lastname = "smith"; using (var client = new httpclient()) { client.baseaddress = new uri("http://myapi.mydomain.com"); client.defaultrequestheaders.accept.clear(); client.defaultrequestheaders.accept.add(new mediatypewithqualityheadervalue("application/json")); client.defaultrequestheaders.authorization = new system.net.http.headers.authenticationheadervalue("bearer", token.accesstoken); **// how send employee object api?** httpresponsemessage response = await client.getasync("api/mycontroller/myaction"); if (response.issuccessstatuscode) { var someobject = await response.content.readasasync<myobjecttype>(); } }

what need perform post api endpoint , serialize employee object json object, so:

var gizmo = new product() { name = "gizmo", cost = 100, category = "widget" }; response = await client.postasjsonasync("api/products", gizmo); if (response.issuccessstatuscode) { // uri of created resource. uri gizmourl = response.headers.location; }

at moment existing code performing request.

httpresponsemessage response = await client.getasync("api/mycontroller/myaction");

i highly recommend take @ article highlights how phone call web api endpoint via c#.

i hope helps.

asp.net asp.net-mvc asp.net-mvc-4 asp.net-web-api asp.net-web-api2

No comments:

Post a Comment