WebAPI 2参数绑定方法

简单类型参数

Example 1: Sending a simple parameter in the Url

[RoutePrefix("api/values")]
public class ValuesController : ApiController
{
  // http://localhost:49407/api/values/example1?id=2
  [Route("example1")]
  [HttpGet]
  public string Get(int id)
  {
     return "value";
  }
}

 

Example 2: Sending simple parameters in the Url

// http://localhost:49407/api/values/example2?id1=1&id2=2&id3=3
[Route("example2")]
[HttpGet]
public string GetWith3Parameters(int id1, long id2, double id3)
{
    return "value";
}

 

Example 3: Sending simple parameters using attribute routing

// http://localhost:49407/api/values/example3/2/3/4
[Route("example3/{id1}/{id2}/{id3}")]
[HttpGet]
public string GetWith3ParametersAttributeRouting(int id1, long id2, double id3)
{
   return "value";
}

 

Example 4: Sending an object in the Url

// http://localhost:49407/api/values/example4?id1=1&id2=2&id3=3
[Route("example4")]
[HttpGet]
public string GetWithUri([FromUri] ParamsObject paramsObject)
{
  return "value:" + paramsObject.Id1;
}
 

Example 5: Sending an object in the Request body

[Route("example5")]
[HttpPost]
public string GetWithBody([FromBody] ParamsObject paramsObject)
{
  return "value:" + paramsObject.Id1;
}

注意 [FromBody] 只能用一次,多于一次将不能正常工作

Calling the method using Urlencoded in the body:

User-Agent: Fiddler
Host: localhost:49407
Content-Length: 32
Content-Type: application/x-www-form-urlencoded

id1=1&id2=2&id3=3

Calling the method using Json in the body:

User-Agent: Fiddler
Host: localhost:49407
Content-Length: 32
Content-Type: application/json

{ "Id1" : 2, "Id2": 2, "Id3": 3}

 

Calling the method using XML in the body

This requires extra code in the Global.asax

protected void Application_Start()
{
   var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
   xml.UseXmlSerializer = true;
The client request is as follows:

User-Agent: Fiddler
Content-Type: application/xml
Host: localhost:49407
Content-Length: 65

<ParamsObject><Id1>7</Id1><Id2>8</Id2><Id3>9</Id3></ParamsObject>

 

 

 

数组和列表(Array,List)

Example 6: Sending a simple list in the Url

// http://localhost:49407/api/values/example6?paramsObject=2,paramsObject=4,paramsObject=9
[Route("example6")]
[HttpGet]
public string GetListFromUri([FromUri] List<int> paramsObject)
{
  if (paramsObject != null)
  {
	return "recieved a list with length:" + paramsObject.Count;
  }

  return "NOTHING RECIEVED...";
}

Example 7: Sending an object list in the Body

// http://localhost:49407/api/values/example8
[Route("example8")]
[HttpPost]
public string GetListFromBody([FromBody] List<ParamsObject> paramsList)
{
  if (paramsList != null)
  {
     return "recieved a list with length:" + paramsList.Count;
  }

  return "NOTHING RECIEVED...";
}

 

Calling with Json:

User-Agent: Fiddler
Content-Type: application/json
Host: localhost:49407
Content-Length: 91

[{"Id1":3,"Id2":76,"Id3":19},{"Id1":56,"Id2":87,"Id3":94},{"Id1":976,"Id2":345,"Id3":7554}]

Calling with XML:

User-Agent: Fiddler
Content-Type: application/xml
Host: localhost:49407
Content-Length: 258

<ArrayOfParamsObject>
<ParamsObject><Id1>3</Id1><Id2>76</Id2><Id3>19</Id3></ParamsObject>
<ParamsObject><Id1>56</Id1><Id2>87</Id2><Id3>94</Id3></ParamsObject>
<ParamsObject><Id1>976</Id1><Id2>345</Id2><Id3>7554</Id3></ParamsObject>
</ArrayOfParamsObject>

 

Example 8: Sending object lists in the Body

[Route("example8")]
[HttpPost]
public string GetListsFromBody([FromBody] List<List<ParamsObject>> paramsList)
{
  if (paramsList != null)
  {
	return "recieved a list with length:" + paramsList.Count;
  }

  return "NOTHING RECIEVED...";
}

This is a little bit different to the previous examples. The body can only send one single object to Web API. Because of this, the lists of objects are wrapped in a list or a parent object.

POST http://localhost:49407/api/values/example8 HTTP/1.1
User-Agent: Fiddler
Content-Type: application/json
Host: localhost:49407
Content-Length: 185

[
 [
  {"Id1":3,"Id2":76,"Id3":19},
  {"Id1":56,"Id2":87,"Id3":94},
  {"Id1":976,"Id2":345,"Id3":7554}
 ],
 [
  {"Id1":3,"Id2":76,"Id3":19},
  {"Id1":56,"Id2":87,"Id3":94},
  {"Id1":976,"Id2":345,"Id3":7554}
 ]
]

 

 

 

 

自定义参数

What if the default parameter binding is not enough? Then you can use the ModelBinder class to change your parameters and create your own parameter formats. You could also use ActionFilters for this. Many blogs exist which already explains how to use the ModelBinder class. See the links underneath.

 

文件和二进制

Files or binaries can also be sent to Web API methods. The articledemonstrates how to do this.

 

参考

http://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/CustomParameterBinding/

http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

http://www.strathweb.com/2013/04/asp-net-web-api-parameter-binding-part-1-understanding-binding-from-uri/

http://www.roelvanlisdonk.nl/?p=3505

http://stackoverflow.com/questions/9981330/how-to-pass-an-array-of-integers-to-a-asp-net-web-api-rest-service

http://stackoverflow.com/questions/14628576/passing-an-json-array-to-mvc-web-api-via-get

时间: 2025-01-09 08:21:32

WebAPI 2参数绑定方法的相关文章

ASP.NET WebAPI 05 参数绑定

ParameterBindingAttribute 在上一篇中重点讲了ModelBinderAttribute的使用场景.这一篇详细的讲一下ModelBinder背后的参数绑定原理. ModelBinderAttribute继承自ParameterBindingAttribute,从命名上就是可以看出ParameterBindingAttribute是对Action参数进行绑定的一种特性.除了ModelBinderAttribute之外,WebAPI还另外定义了ValueProviderAttr

springMVC参数绑定

默认支持的参数类型 处理器形参中添加如下类型的参数处理注解适配器会默认识别并进行赋值.1 HttpServletRequest通过request对象获取请求信息2 HttpServletResponse通过response处理响应信息3 HttpSession通过session对象得到session中存放的对象4 Model通过model向页面传递数据,如下://调用service查询商品信息Items item = itemService.findItemById(id);model.addA

使用ASP.Net WebAPI构建REST服务(四)——参数绑定

默认绑定方式 WebAPI把参数分成了简单类型和复杂类型: 简单类型主要包括CLR的primitive types,(int.double.bool等),系统内置的几个strcut类型(TimeSpan.Guid等)以及string.对于简单类型的参数,默认从URI中获取. 复杂类型的数据也可以直接作为参数传入进来,系统使用media-type formatter进行解析后传给服务函数.对于复杂类型,默认从正文中获取, 例如,对于如下函数 HttpResponseMessage Put(int

WebAPI路由、参数绑定

? 一.测试Web API a)测试Web API可以用来检测请求和返回数据是否正常,可以使用Fiddler.Postman等工具.以Fiddler为例,这是一个http协议调试代理工具,它能够记录客户端和服务器之间的所有 HTTP请求,可以针对特定的HTTP请求,分析请求数据.设置断点.调试web应用.修改请求的数据,甚至可以修改服务器返回的数据. b)Fiddler会默认捕获所有进程的通信,可以在All Processes中Hide All然后在Composer-Parsed选项卡选择需要捕

SpringMvc参数绑定出现乱码解决方法

在SpringMvc参数绑定过程中出现乱码的解决方法 1.post参数乱码的解决方法 在web.xml中添加过滤器 <!-- 过滤器 处理post乱码 --> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class

使用@RequestParam绑定请求参数到方法参数

@RequestParam注解用于在控制器中绑定请求参数到方法参数.用法如下:@RequestMapping public void advancedSearch(   @RequestParam("queryStr") String queryStr,   @RequestParam("showFlag") String showFlag,   @RequestParam("totalnumber") String totalNumber,  

asp.net webapi 参数绑定总结

首先必须得更正下自己一直以来对于get请求和post请求理解的一个误区:get请求只能通过url传参,post请求只能通过body传参. 其实上面的理解是错误的,翻阅了不少资料及具体实践,正确理解应该是:get和post是http协议(规范)定义的和服务器交互的不同方法,get用于从服务器获取资源(安全和幂等),post用于修改服务器上的资源.传参方式和请求方式没有任何关系,get和post请求既可以接受url传参,也可以接收body传参,取决于服务端的参数绑定机制. OK,回到主题,webap

webapi简介及参数绑定

介绍:WebAPI用来开发系统间接口的技术,基于HTTP协议,返回默认是json格式.比wcf简单 更通用,更轻量级,更省流量(json格式):WebAPI尽可能复用MVC路由.ModelBinder.Filter等知识,但只是模仿webapi默认路由机制是通过http请求类型匹配Action(REST风格),而MVC的默认路由机制是通过url匹配Action.可以修改webapi默认路由机制,通过url匹配action Restfull风格:就是基于谓词语义进行通讯协议的设计(利用get.po

ASP.NET WebAPI 11 参数验证

在绑定完Action的所有参数后,WebAPI并不会马上执行该方法,而要对参数进行验证,以保证输入的合法性. ModelState 在ApiController中一个ModelState属性用来获取参数验证结果. public abstract class ApiController : IHttpController, IDisposable { public ModelStateDictionary ModelState { get; } } ApiContext的ModelState属性实