Binding to a dynamic object from a query string in ASP.NET Web API

I would like to bind to a dynamic object from a querystring request in the ASP.NET Web API. Although decorating an action parameter with [FromUri]does work with a normal class, it does not work with a dynamic one (dynamic object is empty).

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

Note that this is necessary for GET requests, so there is no body.

+4
source share
3 answers

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

As long as it does not bind the query parameters to the model, it allows you to access the query parameters dynamically (which sounds like your final goal) through a dictionary-like object.

. .

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;
    }
}    
+5

, . [FormUri] . , .

. , .

"" ​​ , , , .

+3

Web API , Multiple actions were found that match the request Get "" , .

public class House
{
    public string Color { get; set; }
    public double SquareFeet { get; set; }
    public override string ToString()
    {
        return "Color: " + Color + ", Sq. Ft.:" + SquareFeet;
    }
}

public class Car
{
    public string Color { get; set; }
    public double EngineSize { get; set; }
    public override string ToString()
    {
        return "Color: " + Color + ", cc: " + EngineSize;
    }
}

public class ValuesController : ApiController
{
    public string Get([FromUri] bool house, [FromUri] House model)
    {
        return model.ToString();
    }

    public string Get([FromUri] bool car, [FromUri] Car model)
    {
        return model.ToString();
    }
}

Using the code above, the following URLs give the appropriate output:

~ / api / values ​​house = truth &? = White & squarefeet = 1500

<string>Color: white, Sq. Ft.:1500</string>

~ / api / values ​​car = true &? Color = Black & enginesize = 2500

<string>Color: black, cc: 2500</string>
0
source

All Articles