首页 > 解决方案 > Webapi接收带括号的json

问题描述

我只是想了解,我花了几天时间试图解决 POST 操作不起作用的问题(使用 Web Api 和 Angular JS)。我考虑了所有事情,尝试,搜索,甚至将代码更改了一千次。之后,我发现POSTJSON格式如下时有效:

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

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

POST 操作不起作用,它的格式是这样的:

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

我不明白它们之间有什么区别(不管括号[]

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

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

第二个是 JSON 数组吗?

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

班级:

 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; }

        }

在 WebApi 中:

    [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);
                            }


                        }
                    }

标签: c#angularjsasp.net-web-apikendo-grid

解决方案


提到的格式({"Name":"Test","Age":23}[{"Name":"Test","Age":23}])都意味着两个不同的合同。

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

假设如果您{"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 
}

推荐阅读