简体   繁体   中英

How to return data FROM HttpPost to WebApi

I've been passed a specification that is requesting to use an HttpPost request and receive back data - looking from the spec as if it is Form data.

My current WebApi implementation doesn't return any data from the HttpPost request, just the HttpResponse.OK (200) and the location to navigate to.

I've tried a very simple formatter, but this returns xml:

var baseResponse = new BaseResponse() { Something = "Fred" };
HttpResponseMessage response = this.Request.CreateResponse<BaseResponse>(HttpStatusCode.OK, baseResponse);
return response;

and if I add the "application/x-www-form-urlencoded" to the method then I receive back an error:

Could not find a formatter matching the media type 'application/x-www-form-urlencoded'

The sped document shows Key/Value pairs...so I could either generate these as a string, or implement a custom formatter?

e.g.
Header = blah blah 200 OK
Data = Something=Fred&SomethingElse=NotFred&AnotherThing=Banana

However, is there an easier way to achieve this?

In an ASP.NET MVC website, your controller method handling the Post would return ActionResult . The ActionResult could be a JsonResult which could have named parameters.

In WebAPI, you could do something similar by implementing IHttpActionResult to emulate ActionResult.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM