【问题标题】:ApiController Action Failing to parse array from querystringApiController 操作无法从查询字符串解析数组
【发布时间】:2013-08-30 18:11:34
【问题描述】:

使用 Visual Studio 2012.2,MVC4 网络应用程序。

我的 ApiController 有这样的请求:

http://localhost/api/keys?ids[]=1&ids[]=2&ids[]=3

我的印象是以下方法应该能够自动从 ids[] 数组中检索值:

public KeysModel Get(int[] ids){...}

但是,当像上面这样的请求进来时,“ids”参数的值为null。

我已经检查过 HttpContext.Current.Request.QueryString 具有 id 的值,我可以通过这种方式获取它们,但这会使单元测试更加困难。

我也尝试过使用 List ids、[FromUri]、[FromUri(Name="ids[]")]、object ids 和 string ids(有趣的注意......当 ids 是一个字符串变量时,其中的值它是“(集合)”

【问题讨论】:

  • 您可以尝试将您的 uri 更改为这样并尝试查看它是否有效:http://localhost/api/keys?ids=1&ids=2&ids=3 并且您应该使用 [FromUri] 属性装饰参数,因为默认情况下 Web API 会考虑复杂类型来自身体
  • 无法更改 uri。它以这种方式来自 ember,目标是不制作自定义适配器/序列化器,而是屈服于 ember 的意愿。
  • 原来我没有正确使用 [FromUri] (我肯定认为我有......一定是“盯着它看太久”的问题)。
  • 不要在你的查询字符串中使用[],我相信这是一个PHP特有的习惯用法。
  • 不要在查询字符串中多次使用同一个键,这太愚蠢了!

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


【解决方案1】:

结果:

public KeysModel Get([FromUri]int[] ids){...}

毕竟是答案。

不知道我之前在做什么......

【讨论】:

    猜你喜欢
    • 2011-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多