I want to do this, but I want to also be able to pass in arrays into the query string. I\'ve tried things like:
http://www.sitename.com/route?arr[]=this&
Given:
public ValuesController
{
public IACtionResult Get([FromUri]string[] arr)
{
Return Ok(arr.Length);
}
}
The following request will work:
GET /api/values/?arr[0]=a&arr[1]=b&arr[2]=c
I found two problems in your question:
arr
while you Contrller's Action has values
.ModelBinder
can work as expected. Like this:public void DoSomething([FromQuery(Name = "values")] string[] values)
After doing that, everything should work as expected.
I had the same problem with .NET Core 3, while trying to pass in a string Array. I solved it by passing in the query parameter as a temporary json string. I then deserialized the string to the resulting array using Newtonsoft's Json package
using Newtonsoft.Json;
public IActionResult Get([FromQuery(Name = "array")] string arrayJson)
{
List<string> array = JsonConvert.DeserializeObject<List<string>>(arrayJson);
}
Use a parameter name in the query string. If you have an action:
public void DoSomething(string[] values)
Then use values
in the query string to pass an array to a server:
?values=this&values=that
Delimited string is not the standard. Think also about the client if you support swagger or other generators.
For those who wonder about .net core 2.1 bug which receives an empty list, the work around is here: https://github.com/aspnet/Mvc/issues/7712#issuecomment-397003420
It needs a name parameter on FromQuery
[FromQuery(Name = "employeeNumbers")] List<string> employeeNumbers
I had to do something similar to this, but instead of strings, i used a list of long to pass some id for a search. Using a multiple select option, the chosen values are sent to the method (via get) like this:
[HttpGet("[action]")]
public IActionResult Search(List<long> idsSelected)
{
///do stuff here
}
I also use Route("[controller]")
before the class declaration. Works just fine, but the list of items is broken into multiple parameters in the url, as shown below.
http://localhost:5000/Search/idsSelected=1&idsSelected=2