【发布时间】:2012-10-24 01:37:23
【问题描述】:
我们有一个 MVC (MVC4) 应用程序,它有时可能会收到一个 JSON 事件从第 3 方发布到我们的特定 URL(“http://server.com/events/”)。 JSON 事件在 HTTP POST 的正文中,并且正文是严格的 JSON(Content-Type: application/json - 不是在某些字符串字段中带有 JSON 的表单发布)。
如何在控制器主体中接收 JSON 主体?我尝试了以下但没有得到任何东西
[编辑]:当我说 什么都没有得到时,我的意思是 jsonBody 始终为 null,无论我将其定义为 Object 还是 string .
[HttpPost]
// this maps to http://server.com/events/
// why is jsonBody always null ?!
public ActionResult Index(int? id, string jsonBody)
{
// Do stuff here
}
请注意,如果我使用强类型输入参数声明方法,MVC 会执行整个解析和过滤,即
// 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 变体定义(和维护)数百个不同的类。
我正在通过以下 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 }}}
【问题讨论】:
-
那么你将如何使用 if/else 解析数百种不同的 JSON 变体?
-
@TheVillageIdiot:它们每个都作为一个 JSON 对象转储到日志中。所以这就是为什么我只关心它们作为 JSON 对象或字符串 - 不关心它们里面的内容。
标签: asp.net-mvc json post