0

I am having some issues with Web API, and standard documentation didn't help me much..

I have a ProductsController, with a default method GetAllProducts(), which accepts several GET parameters (it was easier to implement that way) for querying.

Now, in another part of the application, I use a jQuery autocomplete plugin, which has to query my webservice and filter the data. Problem is, it expects results in a custom format, which is different than that returned by Web API. I procedeed creating another method, GetProductsByQuery(string query), which should return the data in that format.

Is there any way I can enforce WebAPI to return the data as I want it, without making another Controller?

I am also having problems with the routing table, because all the GETs go straight to the first method, even if I routed the second one to url: "{controller}/query/{query}"

Here is some code:

public class ProductsController : ApiController {

    public IEnumerable<Product> GetAllProducts()
    {
        NameValueCollection nvc = HttpUtility.ParseQueryString(Request.RequestUri.Query);
        // Querying EF with the parameters in the query string

        return returnQuery;
    }

    [System.Web.Mvc.HttpGet]
    public dynamic GetProductsByQuery(string query)
    {
        return SomeCustomObject;
    }

And the routing:

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

        routes.MapRoute(
            name: "Query",
            url: "{controller}/query/{query}");
3
  • Please post your code. Commented Aug 25, 2013 at 15:29
  • Right, missed that. I posted a stripped down version of the code, with what I've tried Commented Aug 25, 2013 at 15:33
  • 1
    You aren't forced to return Products from your ProductsController, you can return whatever you want. Just return your custom object that matches the contract (assuming it expects json output) expected by your caller. Commented Aug 25, 2013 at 21:46

1 Answer 1

1

You need to swap your routes around - any request that matches your second route will match your first route first.

Secondly, look into custom media formatters if you need specific return formats for your data:

http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters

Sign up to request clarification or add additional context in comments.

Comments

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.