WebApi参数传递

c# webapi的参数传递方式:1、查询字符串(query string);2、内容主体(content body)

当然也有cookie或url部分或头部信息(header)等其它传方式,这里仅讨论这两种。

1、查询字符串(query string)

如果是简单数据类型或使用了FromUri特性修饰的参数,将使用查询字符串作为数据源。

例1:因为参数p为复合类型,默认使用request body做为数据源,所以如果想以query string为数据源,则不能省略 FromUri修饰。

 1     /// <summary>
 2     /// <example>
 3     /// 调用方式:
 4     ///     test?p=1&p=2
 5     ///     test?p[]=1,2
 6     /// </example>
 7     /// </summary>
 8     public class Test : ApiController
 9     {
10         public string Post([FromUri]string[] p)
11         {
12             if (p == null)
13                 return "NULL";
14             else if (p.Length == 0)
15                 return "EMPTY";
16             else return string.Join(",", p);
17         }
18     }

 

例2:

 1     /// <summary>
 2     /// <example>
 3     /// 调用方式:
 4     ///     test?p=1
 5     /// </example>
 6     /// </summary>
 7     public class Test : ApiController
 8     {
 9         public string Post(string p)
10         {
11             if (p == null)
12                 return "NULL";
13             else if (p.Length == 0)
14                 return "EMPTY";
15             else return string.Join(",", p);
16         }
17     }

2、内容主体(content body)

如果是复合数据类型或使用了FromBody特性修饰的参数,将使用内容主体作为数据源。在webapi中,body不会被缓存,仅可获取一次,故只能对body接收一次参数,所以不适合传递多参数数据。

例1:x-www-form-urlencoded编码方式时,注意不能带参数名。

 1     /// <summary>
 2     /// <example>
 3     /// post请求头:
 4     ///     Content-Type: application/x-www-form-urlencoded
 5     ///     Cache-Control: no-cache
 6     ///
 7     ///     =v1&=v2
 8     /// </example>
 9     /// </summary>
10     public class TestController : ApiController
11     {
12         public string Post([FromBody]string[] p)
13         {
14             if (p == null)
15                 return "NULL";
16             else if (p.Length == 0)
17                 return "EMPTY";
18             else return string.Join(",", p);
19         }
20     }

例2:Content-Type为json时

 1     /// <summary>
 2     /// <example>
 3     /// post请求头:
 4     ///     Content-Type: application/json
 5     ///     Cache-Control: no-cache
 6     ///
 7     ///     ["v1","v2"]
 8     /// </example>
 9     /// </summary>
10     public class TestController : ApiController
11     {
12         public string Post([FromBody]string[] p)
13         {
14             if (p == null)
15                 return "NULL";
16             else if (p.Length == 0)
17                 return "EMPTY";
18             else return string.Join(",", p);
19         }
20     }

 

转载于:https://www.cnblogs.com/lazyls/p/4642630.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值