MVC controller : get JSON object from HTTP body?

前端 未结 5 559
闹比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: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(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();
    

提交回复
热议问题