【发布时间】:2015-09-10 10:13:35
【问题描述】:
如何在 C# 中的 WebAPI 后端接收 JSON 数据?
我的 JavaScript 前端发送了以下 JSON。
{
"User_Id": 1,
"TotalPrice": 35,
"DeliveryAddress": "At my house",
"CartItems": [
{
"Id": 1009,
"Name": "Superman juni 2014",
"Quantity": 1,
"Price": 35
}
]
}
我有这些课程:
public class PurchaseOrder
{
public List<CartItem> CartItems { get; set; }
public string DeliveryAddress { get; set; }
public int TotalPrice { get; set; }
public int User_Id { get; set; }
}
public class CartItem
{
public int Id { get; set; }
public string Name { get; set; }
public int Quantity { get; set; }
public int Price { get; set; }
}
还有我的 WebAPI 方法:
[System.Web.Mvc.HttpPost]
public bool AddOrder(PurchaseOrder order)
{
// Here I will do something
return true;
}
我的“PurchaseOrder order”对象的结果只有“null”。问题可能是我正在使用 [System.Web.Mvc.HttpPost] 吗?我也尝试过 [System.Web.Http.HttpPost],但得到了相同的结果。 // 马丁
【问题讨论】:
-
您是否在 JavaScript 请求中将 Content-Type 设置为
application/json? -
你能包含完整的 Javascript 请求吗?
-
使用您的数据构建一个名为
order的 javascript 对象,并在发布时使用JSON.stringify。 -
除非您使用 vNext,否则这是错误的
System.Web.Mvc.HttpPost它应该来自Http命名空间我相信不是Mvc一个。其次,这与您的 JavaScript 有关。
标签: c# json asp.net-web-api