• 2018年12月9日

c#的MVC模式Controller如何解析post过来的json数组

public ActionResult SomeAction()
{
try
{
var sr = new StreamReader(Request.InputStream);
var stream = sr.ReadToEnd();
try
{
JArray arrary = JArray.Parse(stream);
foreach (JObject item in arrary)
{
string[] pars = item[“content”].ToString().Trim().Split(‘ ‘);
}
}
catch (Exception e)
{

}
}
catch (Exception e)
{

}
return new JsonResult()
{
Data = new { code = 0, msg = “接收成功” },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}

服务器的某个Action需要接收到一个json数组[{id:1,name:”abc”},{id:2,name:”hello”}],苦于不知道应该用什么参数接收,只能各种百度,最终写出了这个代码,勉强搞定这个功能了。

正常情况post过来的json数据,action都是可以自动解析的,比如给服务器post了个{id:1,name:”abc”},那么Action的声明可以这么写

public ActionResult SomeAction(int id,string name)

{

程序内可以直接调用id和name

}

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注