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获得结果,参数为null。

解决方法

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

将您的操作签名更改为

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

如果你想要模型绑定器从querystring拉模型。

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

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....