nzondlo
nzondlo

Reputation: 4176

Can a Web API controller GETter for query strings be generic?

From Microsoft's CRUD tutorial for their Web API:

Finally, add a method to find products by category:

public IEnumerable<Product> GetProductsByCategory(string category)
{
    return repository.GetAll().Where(
            p => string.Equals(p.Category, category, StringComparison.OrdinalIgnoreCase));
}

If the request URI has a query string, Web API tries to match the query parameters to parameters on the controller method. Therefore, a URI of the form "api/products?category=category" will map to this method.

Is there any way to make this generic? As in GetProductsByWhateverIsInTheURI(string WhateverIsInTheURI) or "api/products?whatever=whatever"?

Thank you.

Upvotes: 1

Views: 2444

Answers (1)

Snixtor
Snixtor

Reputation: 4297

I'm not sure I'd describe it as "generic", but you could just have a catch-all route that does away with parameter binding altogether. This would be a method that will "accept any sort of parameter in one method".

public IEnumerable<string> Get()
{
    List<string> retval = new List<string>();

    var qryPairs = Request.GetQueryNameValuePairs();
    foreach (var q in qryPairs)
    {
        retval.Add("Key: " + q.Key + " Value: " + q.Value);
    }

    return retval;
}

Upvotes: 2

Related Questions