標籤:
首先必須得更正下自己一直以來對於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}]
asp.net webapi 參數綁定總結