MVC controller: get JSON object from HTTP body?

We have an MVC application (MVC4) that can sometimes send JSON events sent by a third party to our specific URL (" http://server.com/events/ "). The JSON event is in the body of the HTTP POST, and the body is strictly JSON ( Content-Type: application/json is not a post form with JSON in some string field).

How can I get the JSON body inside the controller body? I tried the following but got nothing

[Edit] : When I said that I received nothing, I meant that jsonBody is always null, regardless of whether I define it as Object or string .

 [HttpPost] // this maps to http://server.com/events/ // why is jsonBody always null ?! public ActionResult Index(int? id, string jsonBody) { // Do stuff here } 

Note that I know that if I declare a method with a strongly typed input parameter, MVC does all the analysis and filtering, i.e.

 // this tested to work, jsonBody has valid json data // that I can deserialize using JSON.net public ActionResult Index(int? id, ClassType847 jsonBody) { ... } 

However, the JSON that we get is very diverse, so we don’t want to define (and maintain) hundreds of different classes for each variant of JSON.

I check this with the following curl command (with one JSON option here)

 curl -i -H "Host: localhost" -H "Content-Type: application/json" -X POST http://localhost/events/ -d '{ "created": 1326853478, "data": { "object": { "num_of_errors": 123, "fail_count": 3 }}} 
+63
json post asp.net-mvc
Oct 24
source share
5 answers

It seems that if

  • Content-Type: application/json and
  • if the POST body is not bound to the controller input object class

Then MVC does not actually bind the POST body to any particular class. Also, you cannot just get the POST body as an ActionResult parameter (suggested in another answer). Fair. You need to extract it from the request stream yourself and process it.

 [HttpPost] public ActionResult Index(int? id) { Stream req = Request.InputStream; req.Seek(0, System.IO.SeekOrigin.Begin); string json = new StreamReader(req).ReadToEnd(); InputClass input = null; try { // assuming JSON.net/Newtonsoft library from http://json.codeplex.com/ input = JsonConvert.DeserializeObject<InputClass>(json) } catch (Exception ex) { // Try and handle malformed POST body return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } //do stuff } 

Update:

for the Asp.Net kernel, you must add [FromBody] next to the name of your parameter in the controller action for complex JSON data types:

 [HttpPost] public ActionResult JsonAction([FromBody]Customer c) 

Also, if you want to access the body of a request as a string in order to parse it yourself, you should use Request.Body instead of Request.InputStream :

 Stream req = Request.Body; req.Seek(0, System.IO.SeekOrigin.Begin); string json = new StreamReader(req).ReadToEnd(); 
+125
Oct 29 '12 at 6:26
source
β€” -

use Request.Form to get the data

Controller:

  [HttpPost] public ActionResult Index(int? id) { string jsonData= Request.Form[0]; // The data from the POST } 



I am writing this to try

View:

 <input type="button" value="post" id="btnPost" /> <script type="text/javascript"> $(function () { var test = { number: 456, name: "Ryu" } $("#btnPost").click(function () { $.post('@Url.Action("Index", "Home")', JSON.stringify(test)); }); }); </script> 

and write Request.Form[0] or Request.Params[0] in the controller can receive data.

I do not write a <form> tag .

+7
Oct 24 '12 at 5:17
source

Once you define a class (MyDTOClass) that indicates what you expect to receive, it should be as simple as ...

 public ActionResult Post([FromBody]MyDTOClass inputData){ ... do something with input data ... } 

thanks to Julias:

Parsing Json.NET Web Api

Make sure your request is sent with the http header:

Content-Type: application / json

+1
Jul 13 '17 at 2:43 on
source

you can get json string as parameter of your ActionResult and then serialize it with JSON.Net

HERE is shown an example




To receive it in serialized form as a parameter of the controller’s action, you must either write a custom mediator or an OnActionExecuting filter so that the json string is serialized to the model of your choice and is available inside the controller for use.




HERE is an implementation using a dynamic object

0
Oct 24 '12 at 5:26
source

I tried to get my ASP.NET MVC controller to parse some model that I presented to it using Postman .

I needed the following to make it work:

  • controller action

     [HttpPost] [PermitAllUsers] [Route("Models")] public JsonResult InsertOrUpdateModels(Model entities) { // ... return Json(response, JsonRequestBehavior.AllowGet); } 
  • model class

     public class Model { public string Test { get; set; } // ... } 
  • headers for a postman request, in particular Content-Type

    postman headers

  • JSON in request body

    enter image description here

0
Jul 17 '19 at 17:57
source



All Articles