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

Toh*_*hid 41 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
    }
}
Run Code Online (Sandbox Code Playgroud)

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

http://localhost/api/users?firstName=john&LastName=smith&birthDate=1979/01/01
Run Code Online (Sandbox Code Playgroud)

并接收用户的xml结果.

是否可以将参数封装到一个类中,如下所示:

public class MyApiParameters
{
    public string FirstName {get; set;}
    public string LastName {get; set;}
    public DateTime BirthDate {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

然后有:

    public IEnumerable<Users> Get(MyApiParameters parameters)
Run Code Online (Sandbox Code Playgroud)

我已经尝试过,无论何时我试图获得结果http://localhost/api/users?firstName=john&LastName=smith&birthDate=1979/01/01,parameter都是null.

Fil*_*p W 71

默认情况下,从body读取复杂类型,这就是为什么你得到null.

将您的操作签名更改为

 public IEnumerable<Users> Get([FromUri]MyApiParameters parameters)
Run Code Online (Sandbox Code Playgroud)

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

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