asp.net mvc - How to make web API Post method call -
i have solution 2 project , 1 webapi service , mvc project . calling service controller. service has get,post,put methods. in view using submit button , calles post controller method in turn call service . here issue facing is calling method. want fire post method in service
controller post method
[httppost] public actionresult create(test test) { if (modelstate.isvalid) { test objtest = myservice.create(test); if (objtest == null) { return httpnotfound(); } return redirecttoaction("index"); } }
here calls service
**public test create(test test) { string uri = baseuri + "test/"; using (httpclient httpclient = new httpclient()) { task<httpresponsemessage> response = httpclient.postasjsonasync(uri, new stringcontent(jsonconvert.serializeobject(test))); return jsonconvert.deserializeobjectasync<test>(response.result.content.readasstringasync().result).result; } }**
this post
**// post api/test public httpresponsemessage posttest(test test { if (modelstate.isvalid) { db.test.add(test); db.savechanges(); httpresponsemessage response = request.createresponse(httpstatuscode.created, test); response.headers.location = new uri(url.link("defaultapi", new { id = test.testid })); return response; } else { return request.createresponse(httpstatuscode.badrequest); } } **************** **// api/test public ienumerable<test> gettest() { var tests= db.tests; return tests.asenumerable(); }**
it calls above method . new web api service. can 1 guide me proper way , wrong. not using ajax call post method.
this how post data.it's similar request in case since want send post aplicable. notice simple add post data (when compared httpwebrequest)
httpclient.postasync(uri, new stringcontent(data));
Comments
Post a Comment