MVC controller : get JSON object from HTTP body?

前端 未结 5 545
闹比i
闹比i 2020-11-28 06:46

We have an MVC (MVC4) application which at times might get a JSON events POSTed from a 3rd party to our specific URL (\"http://server.com/events/\"). The JSON event is in th

相关标签:
5条回答
  • 2020-11-28 07:20

    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 write 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 controller can get the data.

    I don't write <form> tag in view.

    0 讨论(0)
  • 2020-11-28 07:22

    I've been trying to get my ASP.NET MVC controller to parse some model that i submitted to it using Postman.

    I needed the following to get it to work:

    • controller action

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

      public class Model
      {
          public string Test { get; set; }
          // ...
      }
      
    • headers for Postman's request, specifically, Content-Type

    • json in the request body

    0 讨论(0)
  • 2020-11-28 07:26

    It seems that if

    • Content-Type: application/json and
    • if POST body isn't tightly bound to controller's input object class

    Then MVC doesn't really bind the POST body to any particular class. Nor can you just fetch the POST body as a param of the ActionResult (suggested in another answer). Fair enough. You need to fetch 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 Asp.Net Core, you have to add [FromBody] attrib beside your param name in your controller action for complex JSON data types:

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

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

    Stream req = Request.Body;
    req.Seek(0, System.IO.SeekOrigin.Begin);
    string json = new StreamReader(req).ReadToEnd();
    
    0 讨论(0)
  • 2020-11-28 07:33

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

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

    Thx to Julias:

    Parsing Json .Net Web Api

    Make sure your request is sent with the http header:

    Content-Type: application/json

    0 讨论(0)
  • 2020-11-28 07:35

    you can get the json string as a param of your ActionResult and afterwards serialize it using JSON.Net

    HERE an example is being shown


    in order to receive it in the serialized form as a param of the controller action you must either write a custom model binder or a Action filter (OnActionExecuting) so that the json string is serialized into the model of your liking and is available inside the controller body for use.


    HERE is an implementation using the dynamic object

    0 讨论(0)
提交回复
热议问题