将JSON对象作为参数传递给MVC控制器

Ali*_* No 5 asp.net-mvc json jsonresult

我有以下任意JSON对象(字段名称可能会更改).

  {
    firstname: "Ted",
    lastname: "Smith",
    age: 34,
    married : true
  }
Run Code Online (Sandbox Code Playgroud)

-

public JsonResult GetData(??????????){
.
.
.
}
Run Code Online (Sandbox Code Playgroud)

我知道我可以像JSON对象一样定义一个具有与参数相同的字段名称的类,但我希望我的控制器能够接受具有不同字段名称的任意JSON对象.

Moh*_*hin 6

如果您想将自定义JSON对象传递给MVC操作,那么您可以使用此解决方案,它就像一个魅力.

    public string GetData()
    {
        // InputStream contains the JSON object you've sent
        String jsonString = new StreamReader(this.Request.InputStream).ReadToEnd();

        // Deserialize it to a dictionary
        var dic = 
          Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<String, dynamic>>(jsonString);

        string result = "";

        result += dic["firstname"] + dic["lastname"];

        // You can even cast your object to their original type because of 'dynamic' keyword
        result += ", Age: " + (int)dic["age"];

        if ((bool)dic["married"])
            result += ", Married";


        return result;
    }
Run Code Online (Sandbox Code Playgroud)

此解决方案的真正好处是您不需要为每个参数组合定义新类,除此之外,您可以轻松地将对象转换为其原始类型.

更新

现在,你甚至可以合并你的GET和POST动作方法,因为你的post方法不再有任何参数,就像这样:

 public ActionResult GetData()
 {
    // GET method
    if (Request.HttpMethod.ToString().Equals("GET"))
        return View();

    // POST method 
    .
    .
    .

    var dic = GetDic(Request);
    .
    .
    String result = dic["fname"];

    return Content(result);
 }
Run Code Online (Sandbox Code Playgroud)

并且您可以使用这样的帮助方法来促进您的工作

public static Dictionary<string, dynamic> GetDic(HttpRequestBase request)
{
    String jsonString = new StreamReader(request.InputStream).ReadToEnd();
    return Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(jsonString);
}
Run Code Online (Sandbox Code Playgroud)