asp.net webapi 参数绑定总结

 首先必须得更正下本身一直以来对于get请求和post请求理解的一个误区:get请求只能经过url传参,post请求只能经过body传参。web

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

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

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;
}app

客户端调用调用:post

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

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

服务端:code

[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}]

相关文章
相关标签/搜索