如何开发一个ASP.NET Web API接受一个复杂的对象作为参数?
我有以下的Web API(GET):
I have the following Web API (GET):
public class UsersController : ApiController
{
public IEnumerable<Users> Get(string firstName, string LastName, DateTime birthDate)
{
// Code
}
}
这是一个GET,这样我就可以这样调用它:
It's a GET, so I can call it like this:
http://localhost/api/users?firstName=john&LastName=smith&birthDate=1979/01/01
和接收的用户(S)的XML结果。
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;}
}
和则有:
public IEnumerable<Users> Get(MyApiParameters parameters)
我已经尝试过了,只要我尝试从结果http://localhost/api/users?firstName=john&LastName=smith&birthDate=1979/01/01$c$c>,在参数
为null。
默认情况下复杂的类型从主体读取,这就是为什么你越来越空。
By default complex types are read from body, that's why you are getting null.
您的操作签名更改为
public IEnumerable<Users> Get([FromUri]MyApiParameters parameters)
如果你想模型绑定拉从查询字符串的模式。
if you want the model binder to pull the model from the querystring.
您可以阅读更多有关Web API如何做参数由Mike失速从MSFT优秀的文章中结合 - http://blogs.msdn.com/b/jmstall/archive/2012/04/16/how-webapi-does-parameter-binding.aspx
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