42

I have the following Web API (GET):

public class UsersController : ApiController { public IEnumerable<Users> Get(string firstName, string LastName, DateTime birthDate) { // Code } } 

It's a GET, so I can call it like this:

http://localhost/api/users?firstName=john&LastName=smith&birthDate=1979/01/01 

and receive an xml result of user(s).

Is it possible to encapsulate parameters to one class like this:

public class MyApiParameters { public string FirstName {get; set;} public string LastName {get; set;} public DateTime BirthDate {get; set;} } 

And then have:

 public IEnumerable<Users> Get(MyApiParameters parameters) 

I've tried it and anytime I try to get result from http://localhost/api/users?firstName=john&LastName=smith&birthDate=1979/01/01, the parameter is null.

1 Answer 1

73

By default complex types are read from body, that's why you are getting null.

Change your action signature to

 public IEnumerable<Users> Get([FromUri]MyApiParameters parameters) 

if you want the model binder to pull the model from the querystring.

You can read more about how Web API does parameter binding in the excellent article by Mike Stall from MSFT - http://blogs.msdn.com/b/jmstall/archive/2012/04/16/how-webapi-does-parameter-binding.aspx

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

3 Comments

Nice catch. I know I was missing something! :)
This seems to bite me EVERY SINGLE TIME I come back to Web API development. I wish Swashbuckle would do something to make sure it and Web API were in sync with their assumptions on whether this data comes/goes over as querystring data or body data. And I wish Web API would NOT assume complex types were read from the Body on GET calls - that makes no sense ever and especially not as a default. Thanks Tohid and @Filip - this question has saved me numerous times!
Link is no longer current, but it seems that the default parameter binding method expects the object properties to be passed as the URL parameters, this link is working (for the moment): learn.microsoft.com/en-us/aspnet/web-api/overview/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.