如何在ASP.NET Core Web API中传递int数组

时间:2018-08-23 13:51:02

标签: asp.net-core asp.net-core-webapi

我有这个Web API方法:

[Route("api/[controller]")]
[ApiController]
public class SubjectsController : ControllerBase
{
    [HttpGet("children")]
    public IActionResult GetAllFromChildren([FromQuery]int[] childrenIds)
    {
        // omitted for brevity
    }
}

我正在尝试通过Ajax来传递查询字符串,但是我似乎无法使其正常工作。我的Ajax呼叫看起来像这样:

$.ajax({
    url: "/api/subjects/children?childrenIds=1&childrenIds=2&childrenIds=3",
    method: "GET",
    contentType: "application/json; charset=utf-8"
})

该方法被调用,但是不会填充int数组。我在做什么错了?

1 个答案:

答案 0 :(得分:3)

尝试将Name添加到[FromQuery],因此代码应如下所示:

[Route("api/[controller]")]
[ApiController]
public class SubjectsController : ControllerBase
{
    [HttpGet("children")]
    public IActionResult GetAllFromChildren([FromQuery(Name="childrenIds")]int[] childrenIds)
    {
        // omitted for brevity
    }
}

和这样的ajax网址:

$.ajax({
    url: "/api/subjects/children?childrenIds=1&childrenIds=2&childrenIds=3",
    method: "GET",
    contentType: "application/json; charset=utf-8"
})