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

标签 c# json asp.net-web-api

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

关于c# - 如何在 WebAPI 后端 C# 上接收 JSON 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31022668/

相关文章:

c# - 如何从文本文件中删除逗号的最后一个索引?

C# Parse.com + Facebook 注册

Web API Controller 方法的 LINQ 查询 JOIN 两个表

asp.net-mvc - asp.net MVC/WEB API - 如何存储授权 token

c# - ReadAsAsync 从 Json 数据中获取空值?

C#:实现IDisposable接口(interface)时Dispose方法的内容应该是什么

c# - 使用 iTextSharp 打开另存为窗口

json - swift 在字典中存储 String 和 Int

ios - 通过 IOS 从 ASP.NET Web API 获取 bool 值或字符串

ios - 从NSArray获取行