将数组发布到WebApi操作方法

时间:2015-08-20 08:15:58

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

我正在为客户端应用程序开发WebApi端点。 API有一个带有以下签名的方法:

public async Task<IHttpActionResult> Post([FromBody] int[] employeeIds)

我用来触发此端点的示例POST请求:

Authorization: Bearer [token]
Host: localhost:44301
Content-Length: 16
Content-Type: application/json

[10,20,30,40,50]

这一切都很好,花花公子。问题是客户端应用程序只能发送键/值对。正如您从示例POST请求中看到的那样,我只发送数组的值。

我能想到的唯一解决方案是使用数组作为属性来定义模型,但这会为我的代码库添加一个新类,除了作为容器之外没有其他目的。

我如何克服这个问题?

修改

我正在寻找一种解决方案,允许客户端将数组作为键/值对的值组件发送:

key = [10, 20, 30, 40, 50]

如何将我的方法转换为接受此类请求?

3 个答案:

答案 0 :(得分:1)

您可以像这样使用词典:

public async Task<IHttpActionResult> Post([FromBody] Dictionary<string, int> employeeIds)

然后你可以发送如下的请求

Authorization: Bearer [token]
Host: localhost:44301
Content-Length: 16
Content-Type: application/json

{
    'first': 10,
    'second': 20,
    'third': 30
}

**** **** EDIT

在回复您对我的回答的更新和评论时,每个数组都有一个键。 您可以像这样使用.Net类型Tuple

public async Task<IHttpActionResult> Post([FromBody] Tuple<string, int[]> employeeIds)

然后使用

按代码访问值
string myKey = employeeIds.Item1;
int[] theIds = employeeIds.Item2;

请求如下所示:

Authorization: Bearer [token]
Host: localhost:44301
Content-Length: 16
Content-Type: application/json

{
   Item1: 'OfficeWorkers',
   Item2: [10, 20, 30, 40, 50]
}

然而,这显然不那么具有说服力,并且对于将来使用api /修改代码的其他人而言,元组不太明显。

如果由我决定,我会支持一个小类(仅存在于API层中),它充当一个简单的模型,它保存从API调用接收的数据 - 然后在WebApi代码中 - 映射到一个你正在内部使用的“适当”课程。

答案 1 :(得分:0)

  

Web API支持以各种方式解析内容数据,但它不处理多个发布的内容值。您的问题的解决方案可能是创建一个具有int []类型属性的ViewModel。

在这里,您可以阅读有关此问题的更多信息: Passing array of integers to webapi Method

Posting array of integers to asp.net web api

简而言之,您需要创建具有int []

属性的ViewModel

答案 2 :(得分:0)

如果我认为你的问题是正确的,这是我的示例代码:

GPS

邮差客户:

enter image description here

希望这有帮助!

enter image description here

相关问题