Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read HttpContent in WebApi controller

How can I read the contents on the PUT request in MVC webApi controller action.

[HttpPut] public HttpResponseMessage Put(int accountId, Contact contact) {     var httpContent = Request.Content;     var asyncContent = httpContent.ReadAsStringAsync().Result; ... 

I get empty string here :(

What I need to do is: figure out "what properties" were modified/sent in the initial request (meaning that if the Contact object has 10 properties, and I want to update only 2 of them, I send and object with only two properties, something like this:

{      "FirstName": null,     "LastName": null,     "id": 21 } 

The expected end result is

List<string> modified_properties = {"FirstName", "LastName"} 
like image 682
Marty Avatar asked Sep 19 '12 11:09

Marty


People also ask

How do I get httpContent in Web API controller?

How can I read the contents on the PUT request in MVC webApi controller action. [HttpPut] public HttpResponseMessage Put(int accountId, Contact contact) { var httpContent = Request. Content; var asyncContent = httpContent. ReadAsStringAsync().

Can we return view from WebAPI?

You can return one or the other, not both. Frankly, a WebAPI controller returns nothing but data, never a view page. A MVC controller returns view pages. Yes, your MVC code can be a consumer of a WebAPI, but not the other way around.


1 Answers

By design the body content in ASP.NET Web API is treated as forward-only stream that can be read only once.

The first read in your case is being done when Web API is binding your model, after that the Request.Content will not return anything.

You can remove the contact from your action parameters, get the content and deserialize it manually into object (for example with Json.NET):

[HttpPut] public HttpResponseMessage Put(int accountId) {     HttpContent requestContent = Request.Content;     string jsonContent = requestContent.ReadAsStringAsync().Result;     CONTACT contact = JsonConvert.DeserializeObject<CONTACT>(jsonContent);     ... } 

That should do the trick (assuming that accountId is URL parameter so it will not be treated as content read).

like image 84
tpeczek Avatar answered Sep 30 '22 19:09

tpeczek