问题
I'm using Web API (part of ASP.NET MVC 5), and I'm trying to bind querystring values to a Dictionary<int, bool>
.
My Web API method is simply:
[HttpGet]
[Route("api/items")]
public IQueryable<Item> GetItems(Dictionary<int, bool> cf)
{
// ...
}
If I try to invoke this URL:
/api/items?cf[1009]=true&cf[1011]=true&cf[1012]=false&cf[1015]=true
The parameter cf
is always null
.
How can I pass in a dictionary of values via the QueryString to a Web API method?
回答1:
When you want to pass a dictionary (basically key and value pair) using a query string parameter then you should use format like:
¶meters[0].key=keyName¶meters[0].value=keyValue
In my Action method signature, parameters is defined as:
Dictionary<string,string> parameters
Hope this helps.
I was able to figure this our myself after reading this post from Scott Hanselman. So thanks to Scott!!
Thanks, Nirav
回答2:
There is no built-in way of doing this. On this case, "cf[1009]" is the name of the parameter, not "cf". You can write you own query string parser to achieve what you need. A better signature would be:
/api/items?cf=1009&cf=1011&cf=1015
And you bind it by using:
public IQueryable<Item> GetItems(List<int> cf)
{
// ...
}
回答3:
You can create a ModelBinder for your dictionary, as described on this post:
https://stackoverflow.com/a/22708383
来源:https://stackoverflow.com/questions/29320452/binding-querystring-values-to-a-dictionary