Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 558
John Shedletsky Avatar asked Mar 05 '15 02:03

John Shedletsky


1 Answers

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); 
like image 77
ajzeffer Avatar answered Oct 16 '22 08:10

ajzeffer