Asp.net MVC 和 WebApi 解析复杂JSON

Asp.net MVC 和 WebApi 解析复杂JSON

这个问题困扰了我很久,一直没有找到好的解决办法,今天花了一个下午终于解决了,希望其它人看到这个文章可以少走弯路。

前台javascript:重点 contentType: "application/json",其次JSON.stringify(param)将对象转换为JSON字符串

 1     <script>
 2     $(function () {
 3         var param = { AppId: "app_123", AppSecret: "1235435fdsafdsafdsafd", Scope: ["abc", "def", "fgh"] };
 4         $.ajax({
 5             type: "POST",
 6             url: "http://localhost:5502/OAuth/Token",
 7             cache: false,
 8             contentType: "application/json",
 9             data: JSON.stringify(param),
10             /*data: param,*/
11             dataType: "json",
12             success: function (result) {
13                 console.log(result);
14             }
15         });
16     });
17     </script>  

服务端代码:重点将参数封装为一个参数,使用在参数前面使用[FromBody]特性

 1 public class OAuthController : Controller
 2     {
 3         /// <summary>
 4         /// 获取Token
 5         /// </summary>
 6         /// <returns></returns>
 7         [System.Web.Mvc.HttpPost]
12         public ActionResult Token([FromBody]Client client)
13         {
14             return Json(client);
15         }
16  
17     }
18  
19  
20     public class Client
21     {
22         /// <summary>
23         /// 应用ID
24         /// </summary>
25         public string AppId { get; set; }
26  
27         /// <summary>
28         /// 应用密钥
29         /// </summary>
30         public string AppSecret { get; set; }
31  
32         public List<string> Scope { get; set; }
33     }