I am trying to create a web API. As part of it I want to create a Get method which any accept any number of variable of a particular type.
public class MyController : ControllerBase
{
[HttpGet]
public int[] Get(int[] ids)
{
for(int i = 0; i < ids.Length; i++)
{
ids[i] = ids[i] * 100;
}
return ids;
}
}
When I try to make a get request from postman using
https://localhost:44363/api/executionstatus?ids=1&ids=2&ids=3
I get an error
{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"|39f5d965-4240af31edd27f50.","errors":{"$":["The JSON value could not be converted to System.Int32[]. Path: $ | LineNumber: 0 | BytePositionInLine: 1."]}}
I have also tried with
https://localhost:44363/api/executionstatus?ids=1,2,3
but it is also resulting in the same error. What is the correct way to pass/handle multiple parameters from a get request?
I think if you explicitly mention you want to read the variable from the query string, it will work fine in the method you are describing:
//.net Core
public int[] Get([FromQuery]int[] ids)
//.net Framework
public int[] Get([FromUri]int[] ids)
The call:
https://localhost:44363/api/executionstatus?ids=1&ids=2&ids=3
Maybe you could try with string parameter
[HttpGet]
public int[] Get(string ids)
{
var intIds = ids.Split(',').Select(int.Parse).ToList();
for(int i = 0; i < intIds.Length; i++)
{
intIds[i] = intIds[i] * 100;
}
return intIds;
}
and call your api like this
https://localhost:44363/api/executionstatus?ids=1,2,3
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.