如何开发ASP.NET Web API以接受复杂对象作为参数



我有以下Web API(GET):

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

这是一个GET,所以我可以这样称呼它:

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

并接收用户的xml结果。

是否可以将参数封装为一个类,如

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中获得结果时,parameter都是空的。

默认情况下,复杂类型是从body中读取的,这就是为什么会得到null。

将您的行动签名更改为

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

如果您希望模型绑定器从querystring中提取模型。

您可以在MSFT的Mike Stall的精彩文章中阅读更多关于Web API如何进行参数绑定的内容http://blogs.msdn.com/b/jmstall/archive/2012/04/16/how-webapi-does-parameter-binding.aspx

最新更新