您的位置:首页 > 其它

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修饰。

/// <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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: