Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

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.

question from:https://stackoverflow.com/questions/12377423/how-to-develop-an-asp-net-web-api-to-accept-a-complex-object-as-parameter

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...