1

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.

2
  • What exactly are you trying to make generic? What is the purpose of GetProductsByWhateverIsInTheURI? Commented Nov 5, 2013 at 18:41
  • That particular method is mapped to only handle ?category=_category_ as a query string in the URI. This is mapped to `GetProductsByCategory(string category) because the name of the parameter matches the one queried for in the URI. I was trying to figure out if there's a way to accept any sort of parameter in one generic method. Commented Nov 5, 2013 at 18:45

1 Answer 1

2

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry I missed this a while ago... This is good, but I also need to match the key's value (based on the key's name) against the key with that value in the repository (Like the .Where() up there demonstrates). How could I modify this code to do that? Or am I just not seeing it.
There's a number of ways you could go about that. Something like this should get you started - pastebin.com/Y2qYiRnw

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.