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

时间:2012-09-11 20:27:36

标签: asp.net-mvc-4 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为空。

1 个答案:

答案 0 :(得分:70)

默认情况下,从body中读取复杂类型,这就是你得到null的原因。

将您的操作签名更改为

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

如果您希望模型绑定器从查询字符串中提取模型。

您可以在MSFT的Mike Stall撰写的优秀文章中详细了解Web API如何进行参数绑定 - http://blogs.msdn.com/b/jmstall/archive/2012/04/16/how-webapi-does-parameter-binding.aspx