c# - 如何在 WebAPI 后端 C# 上接收 JSON 数据?

如何在 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
        }
    ]
}

我有这些类(class):

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],但得到了相同的结果。 //马丁

最佳答案

您的请求的 Content-Type 应该是 "application/json"

如果您在请求正文中发布您的 json,则将方法签名更改为

[HttpPost]
public bool AddOrder([FromBody] PurchaseOrder order)
{
}

https://stackoverflow.com/questions/31022668/

相关文章:

php - Laravel 5 Controller 将 JSON 整数作为字符串发送

php - json_encode 不使用 html 字符串作为值

json - 如何自定义来自 spring @Valid 验证的默认错误消息?

ruby - 将 json 解析为对象 ruby

javascript - 如何将输入文件对象序列化为 JSON?

ajax - jquery mobile可折叠和galaxy tab 10.1 json响应给出随机

javascript - JSON.stringify 抛出 RangeError : Invali

json - Spring Boot Actuator 端点的 pretty-print JSON

python - datetime.date(2014, 4, 25) 在 Django 中不是 J

python - Django:使用 Javascript 在我的模板中解析 JSON