Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mvc Web API complex object query via GET

Is there a way to query a web api through "GET", but with complex object in its parameter?

All the examples I have seen so far seems to indicate I would have to use "POST". But I don't want to use "POST", because this is a query, at the same time I don't want a function with 16 arguments because that just screams brittle.

public Product Get(int id, string name, DateTime createdBy, string stockNumber, ... ) 
    { 
          ...
    }

I want the above to be turned into:

public Product Get(ProductQuery query) 
    { 
          ...
    }

Is there a way to do this? And how do you make the HttpClient work with the above service.

like image 921
Alwyn Avatar asked Jan 04 '13 19:01

Alwyn


2 Answers

You could have the ProductQuery parameter be passed [FromUri].

Let's say this is your ProductQuery class:

public class ProductQuery
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime CreatedBy { get; set; }
    public string StockNumber { get; set; }
}

You can annotate your action parameter with [FromUri]...

    public Product Get([FromUri] ProductQuery productQuery)
    {...}

... and have properties of ProductQuery (i.e. Id, Name, ...) can be passed in from the the query string in the Uri:

http://.../api/products?Id=1&Name=Product1&CreatedBy=1/4/2013&StockNumber=ABC0001
like image 52
Maggie Ying Avatar answered Nov 09 '22 03:11

Maggie Ying


You may want to look at the OData support in Web API - perhaps that would do what you want? Depends on how complicated the implementation of your query is!

http://blogs.msdn.com/b/alexj/archive/2012/08/15/odata-support-in-asp-net-web-api.aspx

like image 23
Richard Avatar answered Nov 09 '22 02:11

Richard