Simon Simu
Simon Simu

Reputation: 11

How do I use Dictionary as a parameter with the GET method in Web API?

Here is the URL I've tried so far:

{{url}}/api/items?created[gte]=1&created[lte]=1

And this is the GET method:

[HttpGet]
[Route("api/items")]
public IHttpActionResult GetItems([FromUri]Dictionary<string, int> created)
{
    var message = created["gte"];
    return Ok(""+message);
}

I am unable to access get data from the query parameter.

Upvotes: 0

Views: 2643

Answers (1)

T&#226;n
T&#226;n

Reputation: 1

You can update the method like this:

[HttpGet("api/items")]
public IActionResult GetItems(Dictionary<string, int> created)
{
    return Ok(created);
}

[HttpGet] also supports for Route.

In the url:

https://localhost:44392/api/items?created.key1=1&created.key2=2&created.key3=3

And the result in the page:

{"key1":1,"key2":2,"key3":3}

Syntax: created.key1=1

  • created: This requires a name which matches with the parameter name we typed in the method.

  • created.key1: We create new key in this dictionary, and the key name is key1.

  • created.key1=1: We define the value of the key. This value is 1.

  • &created.key2=2: We continue to add new key to the dictionary with the key is key2, and the value is 2

... same to &created.key3=3

Upvotes: 1

Related Questions