看来,如果
Content-Type: application/json
和- 如果POST正文未与控制器的输入对象类紧密绑定
然后,MVC并没有真正将POST主体绑定到任何特定的类。您也不能仅将POST正文作为ActionResult的参数来获取(在另一个答案中建议)。很公平。您需要自己从请求流中获取它并进行处理。
[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.preplex.com/ input = JsonConvert.DeserializeObject<InputClass>(json) } catch (Exception ex) { // Try and handle malformed POST body return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } //do stuff}更新:
对于Asp.Net Core,
[FromBody]对于复杂的JSON数据类型,您必须在控制器操作中的参数名称旁边添加attrib:
[HttpPost]public ActionResult JsonAction([FromBody]Customer c)
另外,如果您想以字符串形式访问请求正文以自行解析,则应使用
Request.Body代替
Request.InputStream:
Stream req = Request.Body;req.Seek(0, System.IO.SeekOrigin.Begin);string json = new StreamReader(req).ReadToEnd();



