您的位置:首页 > 编程语言 > ASP

asp.net webapi 参数绑定总结

2016-04-06 16:02 489 查看
首先必须得更正下自己一直以来对于get请求和post请求理解的一个误区:get请求只能通过url传参,post请求只能通过body传参。

其实上面的理解是错误的,翻阅了不少资料及具体实践,正确理解应该是:get和post是http协议(规范)定义的和服务器交互的不同方法,get用于从服务器获取资源(安全和幂等),post用于修改服务器上的资源。传参方式和请求方式没有任何关系,get和post请求既可以接受url传参,也可以接收body传参,取决于服务端的参数绑定机制。

OK,回到主题,webapi参数绑定最佳实践,直接上例子:

1:简单类型参数绑定&url传参:

服务端:

[HttpGet]
[HttpPost]
public HttpResponseMessage FinnTest(string name,int age)
{
var json = "{name:'" + name + "',age:" + age + "}";
var resp = new HttpResponseMessage
{
Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json")
};
return resp;
}

客户端调用调用:

post http://localhost:27984/HjkDealer/FinnTest?name=finn&age=88 http/1.1

2:简单类型参数绑定&body传参

服务端:

[HttpGet]
[HttpPost]
public HttpResponseMessage FinnTest2([FromBody]string name, int age)
{
var json = "{name:'" + name + "',age:" + age + "}";
var resp = new HttpResponseMessage
{
Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json")
};
return resp;
}

客户端调用:

post http://localhost:27984/HjkDealer/FinnTest2?age=88 http/1.1
content-type:application/x-www-form-urlencoded;charset=utf-8

=finn

注意红色标注:content-type头部必须,否则name参数不能正确接收;body体如果写成:“name=finn”或“finn”,name参数也不能正确接收,深层次原因尚不清楚

3:复杂类型参数绑定&body传参(复杂类型默认body传参)

public class fiona
{
public string name { get; set; }

public string age { get; set; }
}

[HttpGet]
[HttpPost]
public HttpResponseMessage FinnTest4(fiona fiona)
{
var json = "{name:'" + fiona.name + "',age:" + fiona.age + "}";
var resp = new HttpResponseMessage
{
Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json")
};
return resp;
}

客户端调用:

post http://localhost:27984/HjkDealer/FinnTest4 http/1.1
content-type:application/x-www-form-urlencoded;charset=utf-8

name=finn&age=88

4:List复杂类型参数绑定&body的json方式传参(复杂类型默认body传参)

服务端:

[HttpGet]
[HttpPost]
public HttpResponseMessage FinnTest5(List<fiona> fi)
{
var json = "{name:'" + fi[0].name + "',age:" + fi[0].age + "}";
var resp = new HttpResponseMessage
{
Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json")
};
return resp;
}

客户端调用:

post http://localhost:27984/HjkDealer/FinnTest5 http/1.1
content-type:application/json

[{name:"finn",age:88},{name:"fiona",age:99}]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: