如何在WebAPI后端C#上接收JSON数据? [英] How to receive JSON data on WebAPI backend C#?
问题描述
如何在C#中的WebAPI后端上接收JSON数据?
How do I receive JSON data on my WebAPI backend in C#?
我从我的JavaScript前端发送了以下JSON.
I have the following JSON sent from my JavaScript frontend.
{
"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方法:
And my WebAPI method:
[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],但得到相同的结果. //马丁
I only get "null" as the result for my "PurchaseOrder order" object. Can the problem be that I´m using [System.Web.Mvc.HttpPost]? I have also tried [System.Web.Http.HttpPost], but get the same result. // Martin
推荐答案
您请求的Content-Type
应该为"application/json"
如果您将json发布到请求的正文中,而不是将方法签名更改为
If you post your json in a body of the request than change a method signature to
[HttpPost]
public bool AddOrder([FromBody] PurchaseOrder order)
{
}
这篇关于如何在WebAPI后端C#上接收JSON数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!