Dragos Bobolea
Dragos Bobolea

Reputation: 782

.NET Web API custom return value

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}");

Upvotes: 0

Views: 2306

Answers (1)

Ant P
Ant P

Reputation: 25221

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

Upvotes: 1

Related Questions