10

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.

1
  • 1
    No, you cannot pass a model via a GET request. The common practice is to pass the id to the method and then fetch the remainder of the data from the source. Commented Jan 4, 2013 at 19:08

2 Answers 2

23

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

1 Comment

Sounds great, I can force it to use model binder I suppose.
3

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

3 Comments

I agree with Richard. If it's a public api, you may end up with issues where a client may not support a GET request with a body. Discussed more at stackoverflow.com/questions/11091160/….
Can a POST support OData? Not the restful kind - I guess. This is tough, I need to choose between bad practice and losing out of the box OData support.
I am not sure why you would not want to use OData? If you use a library like AutoMapper, you can expose only the properties of your model that you wish. You can do some pretty complex queries using OData, so I would agree with @Richard and go with Odata.

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.