c# - 在 HTTP POST 中发送数组

标签 c# arrays http asp.net-web-api asp.net-web-api2

我想使用 HTTP POST 在请求正文中发送一个数组作为 JSON 字符串:

{
    {
      A: 0,
      B: 1
    },
    {
      A: 2,
      B: 3
    }
}

我有以下数据结构:

public class Test
    {        
        [Display(Name = "A")]
        [Range(1, 2147483647)]
        [Required]        
        public int A { get; set; }
        [Display(Name = "B")]
        [Range(0, 2147483647)]
        [Required]
        public int B { get; set; }
    }

这是我的 Action :

        [HttpPost]
        [ResponseType(typeof(WriteResponse))]
        [Route("Account/{clientId:int}/Test")]
        public IHttpActionResult PostEventTest(int clientId, [FromBody]Test[] test){}

当我执行此操作时,测试参数为空。 如何通过请求体接收某种类型的数组?

最佳答案

如果Test应该代表整个JSON,那就错了。即使您的完整 JSON 也是错误的,因为它不是数组。正确的 JSON 应该是:

{
    "list": [
      {
          "A": "0",
          "B": "1"
      },
      {
          "A": "2",
          "B": "3"
      }
    ]
}

或者像这样:

{
    "item1": {
      A: 0,
      B: 1
    },
    "Item2": {
      A: 2,
      B: 3
    }
}

为此,您的模型必须更改为。对于第一个示例,您的模型应如下所示:

public class TestModel
{
    public IList<Test> list
    { get; set; }
}

public class Test
{        
        [Display(Name = "A")]
        [Range(1, 2147483647)]
        [Required]        
        public int A { get; set; }
        [Display(Name = "B")]
        [Range(0, 2147483647)]
        [Required]
        public int B { get; set; }
}

对于第二个例子,Test 类是一样的,只有 TestModel 会改变:

public class TestModel
{
    public Test item1
    { get; set; }

    public Test item2
    { get; set; }
}

但只有第一个例子是数组。要测试您的 JSON 是否正确,请使用 jsonlint

编辑

在我的示例中,您不需要 [FromBody] 部分,因为您可以将 TestModel 作为方法的参数传递。在我看来,这更好。

关于c# - 在 HTTP POST 中发送数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31716503/

相关文章:

http - Oauth 仅撤销访问 token

C:通过HTTP请求上传文件到Google Drive的错误408响应

c# - 使用 Lisp 函数将 .NET 插件加载到 AutoCAD 2014

c# - 为什么 this.Hide() 在 Form1_load 事件中不起作用?

c# - 在 C# 中使用字符串调用哈希表

python - 在给定条件的情况下在 numpy 数组中填充值

c++ - std::string 与字节缓冲区(c++ 中的区别)

c# - 从所有 Outlook 联系人文件夹中获取联系人 Microsoft Graph

javascript - 用另一个对象替换数组中的对象,ReactJS

http - "forever"和 "never"是唯一有用的缓存持续时间吗?