MVC控制器:从HTTP正文获取JSON对象?

我们有一个MVC(MVC4)应用程序,有时可能会从第三方获取JSON事件发送到我们的特定URL(“http://server.com/events/”)。 JSON事件在HTTP POST的主体中,并且主体严格为JSON( Content-Type: application/json – 不是在某些string字段中带有JSON的表单发布)。

我怎样才能接收控制器的身体内的JSON身体? 我尝试了以下,但没有得到任何东西

[编辑] :当我说没有得到任何东西,我的意思是说,无论我是否将其定义为Objectstring ,jsonBody始终为空。

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

请注意,我知道如果我声明强types的input参数的方法,MVC做了整个parsing和过滤即

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

但是,我们得到的JSON非常多样化,所以我们不想为每个JSON变体定义(并维护)数百个不同的类。

我正在testing这个通过下面的curl命令(这里有一个JSON的变种)

 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 }}} 

看来,如果

  • Content-Type: application/json
  • 如果POST主体没有紧紧地绑定到控制器的input对象类

那么MVC并没有真正将POST主体绑定到任何特定的类。 你也不能把POST体作为ActionResult的参数(在另一个答案中build议)。 很公平。 您需要自己从请求stream中获取并处理它。

  [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 } 

使用Request.Form获取数据

控制器:

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

我写这个试试

视图:

 <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> 

并在控制器中写入Request.Form[0]Request.Params[0]即可获取数据。

我不写在视图中的<form> tag

你可以得到jsonstring作为你的ActionResult的参数,然后使用JSON.Net序列化它

这里展示了一个例子


为了以序列化的forms接收它作为控制器动作的参数,你必须写一个自定义的模型绑定器或者一个Actionfilter(OnActionExecuting),以便将jsonstring序列化到你喜欢的模型中,并在控制器内部可用身体使用。


是一个使用dynamic对象的实现

一旦你定义了一个类(MyDTOClass),表明你期望得到它应该是像…

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

Thx到Julias:

parsingJson .Net Web Api

确保您的请求与http标头一起发送:

内容types:application / json