John Shedletsky
John Shedletsky

Reputation: 7168

Get the body of a POST request in an MVC Controller Action

I have a WebJob that is posting a JSON object to a controller in my MVC website.

The default ModelBinder is not working correctly in this instance. Rather than troubleshoot the binder, I am perfectly happy to handle the serialization myself.

How do I get the body of the POST request from my controller Action so that I can feed it into JSON.net?

I have tried using a StreamReader on Request.InputStream, but I get an empty string.

Upvotes: 7

Views: 13168

Answers (1)

ajzeffer
ajzeffer

Reputation: 850

I'm using Angular.js $http.Post() to send a json object to my actionresult, and the Model Binding was failing. I used the below code and was able to get the json object posted and then use Newtonsoft for the DeSerialization. Interesting thing is that Newtonsoft didn't throw an error on Deserialization while the default model binding in MVC did.

 var req = Request.InputStream;
 var json = new StreamReader(req).ReadToEnd();
 var result = JsonConvert.DeserializeObject<Model>(json); 

Upvotes: 10

Related Questions