Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind to dynamic object from Query String in ASP.NET Web API

I'd like to bind to a dynamic object from the request querystring in ASP.NET Web API. Whilst decorating the action parameter with [FromUri] works with a normal class, it does not appear to work with dynamic (the dynamic object is empty).

public dynamic Get(string id, [FromUri]dynamic criteria)
{
    return Ok();
}

Note that this needs to work for GET requests so there is no body.

like image 738
Ben Foster Avatar asked Aug 04 '14 12:08

Ben Foster


1 Answers

You might be interested in the GetQueryNameValuePairs extension method (docs).

While it doesn't bind the query parameters to a model, it does allow you to access query parameters in a dynamic way (which sounds like your ultimate goal) via a dictionary-like object.

Also, see this answer.

var dict = new Dictionary<string, string>();
var qnvp = this.Request.GetQueryNameValuePairs();

foreach (var pair in qnvp)
{
    if (dict.ContainsKey(pair.Key) == false)
    {
        dict[pair.Key] = pair.Value;
    }
}    
like image 161
ken Avatar answered Sep 29 '22 09:09

ken