4

I am creating a WebApi and I need to take a key value pairs for my GET endpoint. I found some examples of using dictionary in POST method bus this seems not to work with GET

So far I tried this:

[HttpGet]
public IActionResult Get([FromQuery] Dictionary<string, string> myVar)
{
}

I am using swagger to test the API and if I pass {"key":"value"} I am getting my dictionary with a single pair and value is the entire object I pass in. ({[myVar, {"key":"value"}]})

What is the correct way to pass multiple key value pairs to the WebApi for GET method?

EDIT: The underlying issue was that I was using swagger (swashbuckle) to test my endpoint. And at the moment of this question it doesn't support dynamic query parameters Issue on github. It should support it once OpenApi v3 support is added to swashbucle Issue on github.

Ramūnas
  • 1,494
  • 18
  • 37

1 Answers1

5

You should be able to call the endpoint using the following structure and have the values automatically bound via Web API's built-in binder.

https://example.com/api/values?1=john&2=jane

1 and 2=keys for respective entries in dictionaries. john and jane=values

user1011627
  • 1,741
  • 1
  • 17
  • 25
  • I have tried it using Postman, but I get my dictionary corrucpted with `Key [string]:"myVar" Value [string]:null`. It seems that I am missing something – Ramūnas Sep 18 '18 at 14:23
  • It looks like .NET Core model binder is different that .NET Framework version and it doens't like the previous syntax using the []. I'll update the answer with what appears to work for .NET Core. – user1011627 Sep 18 '18 at 14:36