Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to develop an ASP.NET Web API to accept a complex object as parameter?

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.

like image 590
Tohid Avatar asked Sep 11 '12 20:09

Tohid


People also ask

How do I pass complex objects to Web API?

Best way to pass multiple complex object to webapi services is by using tuple other than dynamic, json string, custom class. No need to serialize and deserialize passing object while using tuple. If you want to send more than seven complex object create internal tuple object for last tuple argument.

How do I pass a class object as parameter in Web API?

Show activity on this post. MakeUser method in the User controller for creating a username and password. UserParameter class for sending the parameters as an object. RunAsync method in console client.

How do you force a Web API to read a complex type from the URL?

Use [FromUri] attribute to force Web API to get the value of complex type from the query string and [FromBody] attribute to get the value of primitive type from the request body, opposite to the default rules.


1 Answers

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

like image 117
Filip W Avatar answered Sep 27 '22 21:09

Filip W