【问题标题】:API Action - The value '1,2' is not valid [duplicate]API 操作 - 值“1,2”无效 [重复]
【发布时间】:2019-10-04 15:09:27
【问题描述】:

使用 Asp.Net Core 2.2 我正在使用以下方式调用 API:

products?productsIds=1,2&offset=10&limit=4

但我收到有关 productsIds 模型绑定的错误:

The value '1,2' is not valid.

我尝试使用productsIds=1,在这种情况下它可以工作。

OffsetLimit 也得到正确的值...

API 模型和操作是:

public class Request {
  public IList<Int32> ProductsIds { get; set; }
  public Int32 Limit { get; set; }
  public Int32 Offset { get; set; }
}

[ApiController]
public class ProductController : ControllerBase {

  [HttpGet("products")]
  public async Task<IActionResult> Get([FromQuery]Request request) {
    // Action code
  }

}

我错过了什么?

更新

这与Question 不同,因为该问题中提出的解决方案使用[FromUri]

属性[FromUri] 在 ASP.NET Core 2.2 中不可用 ApiController (Microsoft Docs)。

【问题讨论】:

  • [FromQuery]Request 请求中有数据吗?
  • 你是说其他参数?是的,他们假设正确的值。我添加了一些更多信息来可能会提出问题。事实上,如果我使用productsIds=1,那么它可以工作。
  • 你可以试试 HttpContext.Request.Query["ProductsIds"] 看看是否有效?
  • 更新:是的,它有效...我得到一个字符串“1,2”

标签: c# asp.net-core .net-core asp.net-core-mvc asp.net-core-2.2


【解决方案1】:

如果您想将 List 作为 GET 参数传递,请使用以下查询

products?productsIds=1&productsIds=2

【讨论】:

    【解决方案2】:

    试试这个你可以使用 HttpContext.Request.Query 来获取参数

    喜欢这个

    HttpContext.Request.Query["ProductsIds"]
    

    【讨论】:

    • 但我不想使用 HttpContext.Request.Query["ProductsIds"] ...我希望自动完成绑定,但我不明白为什么 ASP.NET 核心不这样做绑定一个简单的 Ints 列表。
    • 我了解,但据我所知,FromQuery 无法获取数组,因此您必须使用这种方式
    猜你喜欢
    • 2012-08-22
    • 1970-01-01
    • 2011-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-04
    相关资源
    最近更新 更多