c# - Webapi接收带括号的json
问题描述
我只是想了解,我花了几天时间试图解决 POST 操作不起作用的问题(使用 Web Api 和 Angular JS)。我考虑了所有事情,尝试,搜索,甚至将代码更改了一千次。之后,我发现POST
当JSON
格式如下时有效:
{"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);
}
}
}
解决方案
提到的格式({"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
}
推荐阅读
- apache-kafka - Kafka-connect FileStreamSourceConnector 不产生主题
- excel - 在excel中取消选择一行
- laravel - Laravel 分页太慢了
- javascript - jQuery根据选择的值显示文本框
- node.js - 如何在安装 laravel webpack 时修复 errno 71?
- django - 重写 BaseInlineFormset 的删除函数
- java - 如何将子类实例分配给通用(扩展父)对象?
- javascript - TypeError:无法读取反应组件中未定义的属性“getFieldDecorator”
- heatmap - Python Folium HeatMapWithTime:跨多个数据层的一次滑块
- react-native - 在循环内被起诉时,不会为正确的项目调用 onLayout