1

I cannot seem to pass an array of values to my Web API method for some reason. Here is my code:

[HttpGet("api/values/get/{ids}")]
public JsonResult GetValues(string[] valueIds)
{
   //Do something
}

I have tried calling this via the following URLs:

When I call it via the following URLs, I get no 404 and the method is actually called, however, the array is empty:

I have also tried adding the Attribute [FromQuery] to the front of my parameters in the method signatures like this:

public JsonResult GetValues([FromQuery]string[] valueIds)

I cannot seem to get it to work even though every tutorial out there says it should. Ripping my hair out here.

LeonidasFett
  • 3,052
  • 4
  • 46
  • 76

3 Answers3

3

Remove {ids} prefix because the action selector expects ids parameter but you don't pass it in the action.

[HttpGet("api/values/get")]
public JsonResult GetValues(string[] valueIds)
{
   //Do something
}

And apply the request like this;

http://localhost:5001/api/values/get?valueIds=das&valueIds=ewq
lucky
  • 12,734
  • 4
  • 24
  • 46
  • This works. But I don't understand why it works when I pass only a single parameter. For example: [HttpGet("api/values/get/byparent/{parentId}")]. When I call this method with the URL http://localhost:5001/api/values/byparent/dsadasda, the method gets called and the parameter is passed. – LeonidasFett Jan 22 '18 at 17:25
  • "dsadasda" is passed as "parentId" parameter. But in the question case, there is no parameter with named "ids". – lucky Jan 22 '18 at 17:27
1

So let's break appart what you have:

[HttpGet("api/values/get/{ids}")]
public JsonResult GetValues(string[] valueIds)
{
   //Do something
}
  1. I would reccomend removing the /get because your method of request is get in HttpGet
  2. Your specified route implies a passed ids(it's just a variable same as get it can only be singular) i.e:

http://localhost:5001/api/values/get/id

The examples that you have shown.

http://localhost:5001/api/values/get/?valueIds=das&valueIds=ewq

get/?valueIds=das&valueIds=ewq doesn't even specify{ids}

so far your route of /get/{ids} is redundant.

Try

[HttpGet("api/values")]
public JsonResult GetValues(string[] valueIds)
{
   //Do something
}

Query: http://localhost:5001/api/values?valueIds=das&valueIds=ewq

I'd recommend to read up on REST API naming conventions

Anton Toshik
  • 2,621
  • 2
  • 19
  • 42
0

Correct me if I am wrong but I think you need to name the query params with the []-Suffix. Like that:

http://localhost:5001/api/values/get?valueIds[]=das&valueIds[]=ewq

Otherwise you can easily check what your API except with the UrlHelper. Just generate yourself an url:

var url = Url.Action("GetValues", new { valueIds = new [] { "das", "ewq" } });

Meikel
  • 314
  • 2
  • 12