WebApi参数传递
2015-07-13 13:20
267 查看
c# webapi的参数传递方式:1、查询字符串(query string);2、内容主体(content body)
当然也有cookie或url部分或头部信息(header)等其它传方式,这里仅讨论这两种。
1、查询字符串(query string)
如果是简单数据类型或使用了FromUri特性修饰的参数,将使用查询字符串作为数据源。
例1:因为参数p为复合类型,默认使用request body做为数据源,所以如果想以query string为数据源,则不能省略 FromUri修饰。
例2:
2、内容主体(content body)
如果是复合数据类型或使用了FromBody特性修饰的参数,将使用内容主体作为数据源。在webapi中,body不会被缓存,仅可获取一次,故只能对body接收一次参数,所以不适合传递多参数数据。
例1:x-www-form-urlencoded编码方式时,注意不能带参数名。
例2:Content-Type为json时
当然也有cookie或url部分或头部信息(header)等其它传方式,这里仅讨论这两种。
1、查询字符串(query string)
如果是简单数据类型或使用了FromUri特性修饰的参数,将使用查询字符串作为数据源。
例1:因为参数p为复合类型,默认使用request body做为数据源,所以如果想以query string为数据源,则不能省略 FromUri修饰。
/// <summary> /// <example> /// 调用方式: /// test?p=1&p=2 /// test?p[]=1,2 /// </example> /// </summary> public class Test : ApiController { public string Post([FromUri]string[] p) { if (p == null) return "NULL"; else if (p.Length == 0) return "EMPTY"; else return string.Join(",", p); } }
例2:
/// <summary> /// <example> /// 调用方式: /// test?p=1 /// </example> /// </summary> public class Test : ApiController { public string Post(string p) { if (p == null) return "NULL"; else if (p.Length == 0) return "EMPTY"; else return string.Join(",", p); } }
2、内容主体(content body)
如果是复合数据类型或使用了FromBody特性修饰的参数,将使用内容主体作为数据源。在webapi中,body不会被缓存,仅可获取一次,故只能对body接收一次参数,所以不适合传递多参数数据。
例1:x-www-form-urlencoded编码方式时,注意不能带参数名。
/// <summary> /// <example> /// post请求头: /// Content-Type: application/x-www-form-urlencoded /// Cache-Control: no-cache /// /// =v1&=v2 /// </example> /// </summary> public class TestController : ApiController { public string Post([FromBody]string[] p) { if (p == null) return "NULL"; else if (p.Length == 0) return "EMPTY"; else return string.Join(",", p); } }
例2:Content-Type为json时
/// <summary> /// <example> /// post请求头: /// Content-Type: application/json /// Cache-Control: no-cache /// /// ["v1","v2"] /// </example> /// </summary> public class TestController : ApiController { public string Post([FromBody]string[] p) { if (p == null) return "NULL"; else if (p.Length == 0) return "EMPTY"; else return string.Join(",", p); } }
相关文章推荐
- UML建模之时序图(Sequence Diagram)
- notification-应用实例
- 如何解决adb rejected install command with:
- Linux-----Ubuntu Server安装图形界面
- UVA 10491 Cow and Cars
- 解决bootstrap的tooltip插件不能自动定位不是相对于浏览器窗口定位的问题
- JAVA反射学习之——基本学习
- 中国黑客榜
- 排列组合问题:n个数中取m个(Golang实现)
- GRE写作必备句型
- 053第425题
- x的平方根
- 深入理解-HashMap
- Nagios 监控系统架设全攻略
- hdu 4496 D-City(并查集)
- leetCode 49.Anagrams (回文构词法) 解题思路和方法
- iOS-MD5加密
- ONLY三行脚本, SQL数据恢复到指定时间点
- GRE写作必备句型
- 博客前记