Pass Array into ASP.NET Core Route Query String

前端 未结 8 1409
既然无缘
既然无缘 2020-12-05 04:28

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&         


        
相关标签:
8条回答
  • 2020-12-05 05:00

    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
    
    0 讨论(0)
  • 2020-12-05 05:01

    I found two problems in your question:

    1. Your query has parameters named arr while you Contrller's Action has values.
    2. I don't know why, but you gotta name your parameter (as answered here) so the Asp .NET ModelBinder can work as expected. Like this:
    public void DoSomething([FromQuery(Name = "values")] string[] values)
    

    After doing that, everything should work as expected.

    0 讨论(0)
  • 2020-12-05 05:02

    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);
    }
    
    0 讨论(0)
  • 2020-12-05 05:14

    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
    
    0 讨论(0)
  • 2020-12-05 05:19

    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
    
    0 讨论(0)
  • 2020-12-05 05:22

    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
    
    0 讨论(0)
提交回复
热议问题