MVC 控制器:从 HTTP 正文获取 JSON 对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13041808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MVC controller : get JSON object from HTTP body?
提问by DeepSpace101
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 the body of the HTTP POST and the body is strictly JSON (Content-Type: application/json- not a form-post with JSON in some string field).
我们有一个 MVC (MVC4) 应用程序,该应用程序有时可能会从第 3 方发布到我们特定 URL(“ http://server.com/events/”)的 JSON 事件。JSON 事件位于 HTTP POST 的正文中,并且正文是严格的 JSON(Content-Type: application/json- 不是在某些字符串字段中带有 JSON 的表单帖子)。
How can I receive the JSON body inside the controller's body? I tried the following but didn't get anything
如何在控制器主体内接收 JSON 主体?我尝试了以下但没有得到任何东西
[Edit]: When I say didn't get anythingI meant that jsonBody is always null regardless of whether I define it as Objector string.
[编辑]:当我说没有得到任何东西时,我的意思是 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
}
Note that I know if I give declare the method with a strongly typed input parameter, MVC does the whole parsing and filtering i.e.
请注意,我知道如果我使用强类型输入参数声明方法,MVC 会完成整个解析和过滤,即
// this tested to work, jsonBody has valid json data
// that I can deserialize using JSON.net
public ActionResult Index(int? id, ClassType847 jsonBody) { ... }
However, the JSON we get is very varied, so we don't want to define (and maintain) hundreds of different classes for each JSON variant.
然而,我们得到的 JSON 是多种多样的,所以我们不想为每个 JSON 变体定义(和维护)数百个不同的类。
I'm testing this by the following curlcommand (with one variant of the JSON here)
我正在通过以下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 }}}
回答by DeepSpace101
It seems that if
看来,如果
Content-Type: application/jsonand- if POST body isn't tightly bound to controller's input object class
Content-Type: application/json和- 如果 POST 主体没有与控制器的输入对象类紧密绑定
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.
然后 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.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:
对于 Asp.Net Core,[FromBody]对于复杂的 JSON 数据类型,您必须在控制器操作中的参数名称旁边添加attrib:
[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.Bodyinstead of Request.InputStream:
此外,如果您想将请求正文作为字符串访问以自己解析它,则应使用Request.Body代替Request.InputStream:
Stream req = Request.Body;
req.Seek(0, System.IO.SeekOrigin.Begin);
string json = new StreamReader(req).ReadToEnd();
回答by ChunHao Tang
use Request.Formto get the Data
用于Request.Form获取数据
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.
并写入Request.Form[0]或Request.Params[0]在控制器中可以获取数据。
I don't write <form> tagin view.
我不写<form> tag。
回答by andrew pate
Once you define a class (MyDTOClass) indicating what you expect to receive it should be as simple as...
一旦你定义了一个类(MyDTOClass),表明你期望收到它应该像......
public ActionResult Post([FromBody]MyDTOClass inputData){
... do something with input data ...
}
Thx to Julias:
感谢朱莉娅斯:
Make sure your request is sent with the http header:
确保您的请求与 http 标头一起发送:
Content-Type: application/json
内容类型:应用程序/json
回答by Eric
I've been trying to get my ASP.NET MVC controllerto parse some model that i submitted to it using Postman.
我一直在尝试让我的ASP.NET MVC 控制器解析我使用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-Typejson in the request body
回答by Eric
you can get the json string as a param of your ActionResultand afterwards serialize it using JSON.Net
您可以获取 json 字符串作为您的参数,ActionResult然后使用JSON.Net对其进行序列化
HEREan 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.
为了以序列化形式接收它作为控制器操作的参数,您必须编写自定义模型绑定器或操作过滤器(OnActionExecuting),以便将 json 字符串序列化为您喜欢的模型并在控制器内可用体供使用。
HEREis an implementation using the dynamic object
这里是使用动态对象的实现


