How to pass an array of int in ASP.NET Core Web API

霸气de小男生 提交于 2019-12-13 16:32:34

问题


I have this Web API method:

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

I'm trying to call this via Ajax passing in an query string but I can't seem to get it to work. My Ajax call looks like this:

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

The method is called but it the int array does not get populated. What am I doing wrong?


回答1:


Try add Name to [FromQuery], so the code should look like this:

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

and ajax url like this:

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


来源:https://stackoverflow.com/questions/51987428/how-to-pass-an-array-of-int-in-asp-net-core-web-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!