模型
public class modelVenta {
public int idvendedor { get; set; }
public int idcliente { get; set; }
public int idproducto { get; set; }
public int cantidad { get; set; }
public decimal precio { get; set; }
public DateTime fecha { get; set; }
}
public class modelVentas {
public List<string> modeloVenta { get; set; }
}
Controller
[HttpPut]
[Route("api/ventas/Add")]
public HttpResponseMessage putVentas( List<modelVentas> data)
{
return new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
}
JSON
var data = [{
"idvendedor": 1,
"idcliente": 1,
"idproducto": 1,
"cantidad": 2,
"precio": 12.0,
"fecha": 1476445327124
}, {
"idvendedor": 1,
"idcliente": 1,
"idproducto": 2,
"cantidad": 4,
"precio": 23.0,
"fecha": 1476445327124
}, {
"idvendedor": 1,
"idcliente": 1,
"idproducto": 1,
"cantidad": 4,
"precio": 35.0,
"fecha": 1476445327124
}];
发送数据
$http.put("http://localhost:54233/api/ventas/Add", JSON.stringify({
modeloVenta: data
})).then(function () {
toastr.info('Elemento insertado correctamente');
});
我验证了 http://jsonlint.com/ 中的 Json没关系,但每次我从 AngularJS 发送时,api Controller web 总是收到 Null。 请社区,有人可以帮我解决这个问题吗?
最佳答案
你的 putVentas()
方法期待一个 List<modelVentas>
- 使用 modelVentas
简单地拥有 List<string>
的属性.
您发送的 JSON 实际上是一个 List<modelVenta>
,DefaultModelBinder 将尝试从它收到的 JSON 数据反序列化为您在签名中指定的类型。
这就是为什么 data
是null
,因为它不会转换为方法签名所期望的类型。
您的 JSON 正试图传递 modelVenta
的列表方法。
要解决此问题,您需要更新 API 方法以匹配 JSON 发送的类型。将 API 方法的签名更改为:
public HttpResponseMessage putVentas(List<modelVenta> data)
{
// do something with the data
return new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
}
你的 DefaultModelBinder 应该知道你正在传递 List<modelVenta>
相反。
关于c# - Web Api 2 接收 json 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40106031/