Webapi 接收 json 带括号

Webapi receive json with brackets

我只是想明白, 我花了几天时间试图解决 POST 操作不工作的问题(使用 Web Api & Angular JS)。 我考虑了一切,尝试,搜索,甚至更改代码一千次。之后,我发现POSTJSON格式是这样的时候起作用:

{"Name":"Test","Age":23}

但如果我使用 JSON.stringify(options.models);

POST操作失败,格式如下:

[{"Name":"Test","Age":23}]

不明白他们有什么区别(不考虑括号[]

为什么第一个有效而第二个无效?

有没有办法使第二种格式起作用?

第二个是JSON的数组吗?

不应该 JSON.stringify(options.models) return JSON 格式吗?

Class:

 public class EmployeesData
        {
            public EmployeesData() { }
            public EmployeesData(int Id, string Name, int Age, int Phone,string Job, string Department)
            {   this.ID = Id;
                this.Name = Name;
                this.Age = Age;
                this.Phone = Phone;
                this.Job = Job;
                this.Department = Department;}

            [Required]
            public int ID { get; set; }
            public string Name { get; set; }
            public int Age { get; set; }

        }

在网络中Api:

    [HttpPost]
        [ResponseType(typeof(EmployeesData))]

        public async Task<IHttpActionResult> Post([FromBody]EmployeesData employeesData) 
{
            if (!ModelState.IsValid) {
              return BadRequest(ModelState);}

            db.Employees.Add(employeesData);
            await db.SaveChangesAsync();

            return CreatedAtRoute("DefaultApi", new { id = employeesData.ID }, employeesData);
        }

在Angularjs:

parameterMap: function(options, operation) {
        if (operation !== "read") {
             console.log(kendo.stringify(options));
              console.log(JSON.stringify(options.models)); // Not work because of []
             var R = JSON.stringify(options.models).replace(/]|[[]/g, ''); // work I removed []
                                console.log(operation + R);

                             return (R);
                            }


                        }
                    }

上述两种格式({"Name":"Test","Age":23}[{"Name":"Test","Age":23}])表示两种不同的合同。

第一个只是一个对象,第二个是对象集合。

假设如果您从 angular 发送 {"Name":"Test","Age":23} 那么您的 Api 控制器方法应该像

public void Demo(Test test)
{
  ///code here 
}

其中测试将是

public class Test 
{
   public string Name {get;set;}
   public int Age {get;set;}
}

如果您发送 [{"Name":"Test","Age":23}] 那么您的控制器应该像

public void Demo(ICollection<Test> test)
{
  ///code here 
}