如何开发一个ASP.NET Web API接受一个复杂的对象作为参数? [英] How to develop an ASP.NET Web API to accept a complex object as parameter?

查看:83
本文介绍了如何开发一个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)

我已经尝试过了,只要我尝试从结果<$c$c>http://localhost/api/users?firstName=john&LastName=smith&birthDate=1979/01/01,在参数为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优秀的文章中结合 - <一个href=\"http://blogs.msdn.com/b/jmstall/archive/2012/04/16/how-webapi-does-parameter-binding.aspx\">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

这篇关于如何开发一个ASP.NET Web API接受一个复杂的对象作为参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆