如何在 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 订单"对象,我只得到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屋!