本篇通過get、post、put、delete四種請(qǐng)求方式分別談?wù)劵A(chǔ)類型(包括int/string/datetime等)、實(shí)體、數(shù)組等類型的參數(shù)如何傳遞。
一、get請(qǐng)求
1、基礎(chǔ)類型參數(shù)
[HttpGet]
public string GetAllChargingData(int id, string name)
{
return "ChargingData" + id;
}
$.ajax({
type: "get",
url: "http://localhost:27221/api/Charging/GetAllChargingData",
data: { id: 1, name: "Jim", bir: "1988-09-11"},
success: function (data, status) {
if (status == "success") {
$("#div_test").html(data);
}
}
});
2、實(shí)體作為參數(shù)
如果我們在get請(qǐng)求時(shí)想將實(shí)體對(duì)象做參數(shù)直接傳遞到后臺(tái),這樣是不可行的。原來,get請(qǐng)求的時(shí)候,默認(rèn)是將參數(shù)全部放到了url里面直接以string的形式傳遞的,后臺(tái)自然接不到了。
正確傳參方式:
$.ajax({
type: "get",
url: "http://localhost:27221/api/Charging/GetByModel",
contentType: "application/json",
data: { strQuery: JSON.stringify({ ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" }) },
success: function (data, status) {
if (status == "success") {
$("#div_test").html(data);
}
}
});
[HttpGet]
public string GetByModel(string strQuery)
{
TB_CHARGING oData = Newtonsoft.Json.JsonConvert.DeserializeObject<TB_CHARGING>(strQuery);
return "ChargingData" + oData.ID;
}
3、數(shù)組作為參數(shù)
一般get請(qǐng)求不建議將數(shù)組作為參數(shù),因?yàn)槲覀冎纆et請(qǐng)求傳遞參數(shù)的大小是有限制的,最大1024字節(jié),數(shù)組里面內(nèi)容較多時(shí),將其作為參數(shù)傳遞可能會(huì)發(fā)生參數(shù)超限丟失的情況。
4、“怪異”的get請(qǐng)求
為什么會(huì)說get請(qǐng)求“怪異”呢?我們先來看看下面的兩種寫法對(duì)比。
(1)WebApi的方法名稱以get開頭
$.ajax({
type: "get",
url: "http://localhost:27221/api/Charging/GetByModel",
contentType: "application/json",
data: { strQuery: JSON.stringify({ ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" }) },
success: function (data, status) {
if (status == "success") {
$("#div_test").html(data);
}
}
});
[HttpGet]
public string GetByModel(string strQuery)
{
TB_CHARGING oData = Newtonsoft.Json.JsonConvert.DeserializeObject<TB_CHARGING>(strQuery);
return "ChargingData" + oData.ID;
}
這是標(biāo)準(zhǔn)寫法,后臺(tái)加[HttpGet],參數(shù)正常得到。
為了對(duì)比,我將[HttpGet]去掉,然后再調(diào)用
//[HttpGet]
public string GetByModel(string strQuery)
{
TB_CHARGING oData = Newtonsoft.Json.JsonConvert.DeserializeObject<TB_CHARGING>(strQuery);
return "ChargingData" + oData.ID;
}
貌似沒有任何問題!有人就想,那是否所有的get請(qǐng)求都可以省略掉[HttpGet]這個(gè)標(biāo)注呢。我們試試便知。
(2)WebApi的方法名稱不以get開頭
我們把之前的方法名由GetByModel改成FindByModel,這個(gè)再正常不過了,很多人查詢就不想用Get開頭,還有直接用Query開頭的。這個(gè)有什么關(guān)系嗎?
$.ajax({
type: "get",
url: "http://localhost:27221/api/Charging/FindByModel",
contentType: "application/json",
data: { strQuery: JSON.stringify({ ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" }) },
success: function (data, status) {
if (status == "success") {
$("#div_test").html(data);
}
}
});
[HttpGet]
public string FindByModel(string strQuery)
{
TB_CHARGING oData = Newtonsoft.Json.JsonConvert.DeserializeObject<TB_CHARGING>(strQuery);
return "ChargingData" + oData.ID;
}
貌似又可行,沒有任何問題啊。根據(jù)上面的推論,我們?nèi)サ鬧HttpGet]也是可行的,好,我們注釋掉[HttpGet],運(yùn)行起來試試。
如果這種情況下,再把[HttpGet]注釋掉,數(shù)據(jù)就接收不到了。
最后結(jié)論:所有的WebApi方法最好是加上請(qǐng)求的方式([HttpGet]/[HttpPost]/[HttpPut]/[HttpDelete]),不要偷懶,這樣既能防止類似的錯(cuò)誤,也有利于方法的維護(hù),別人一看就知道這個(gè)方法是什么請(qǐng)求。
二、post請(qǐng)求
在WebApi的RESETful風(fēng)格里面,API服務(wù)的增刪改查,分別對(duì)應(yīng)著http的post/delete/put/get請(qǐng)求。我們下面就來說說post請(qǐng)求參數(shù)的傳遞方式。
1、基礎(chǔ)類型參數(shù)
(1)傳遞一個(gè)參數(shù)
post請(qǐng)求的基礎(chǔ)類型的參數(shù)和get請(qǐng)求有點(diǎn)不一樣,我們知道get請(qǐng)求的參數(shù)是通過url來傳遞的,而post請(qǐng)求則是通過http的請(qǐng)求體中傳過來的,WebApi的post請(qǐng)求也需要從http的請(qǐng)求體里面去取參數(shù)。
$.ajax({
type: "post",
url: "http://localhost:27221/api/Charging/SaveData",
data: { "": "Jim" },
success: function (data, status) {}
});
[HttpPost]
public bool SaveData([FromBody]string NAME)
{
return true;
}
我們一般的通過url取參數(shù)的機(jī)制是鍵值對(duì),即某一個(gè)key等于某一個(gè)value,而這里的FromBody和我們一般通過url取參數(shù)的機(jī)制則不同,它的機(jī)制是=value,沒有key的概念,并且如果你寫了key(比如你的ajax參數(shù)寫的{NAME:"Jim"}),后臺(tái)反而得到的NAME等于null。不信你可以試試。
(2)傳遞多個(gè)參數(shù)
傳遞多個(gè)參數(shù),使用dynamic是一個(gè)很不錯(cuò)的選擇。
$.ajax({
type: "post",
url: "http://localhost:27221/api/Charging/SaveData",
contentType: 'application/json',
data: JSON.stringify({ NAME: "Jim",DES:"備注" }),
success: function (data, status) {}
});
[HttpPost]
public object SaveData(dynamic obj)
{
var strName = Convert.ToString(obj.NAME);
return strName;
}
2、實(shí)體作為參數(shù)
(1)單個(gè)實(shí)體作為參數(shù)
上面我們通過dynamic類型解決了post請(qǐng)求基礎(chǔ)類型數(shù)據(jù)的傳遞問題,那么當(dāng)我們需要傳遞一個(gè)實(shí)體作為參數(shù)該怎么解決呢?
$.ajax({
type: "post",
url: "http://localhost:27221/api/Charging/SaveData",
data: { ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" },
success: function (data, status) {}
});
[HttpPost]
public bool SaveData(TB_CHARGING oData)
{
return true;
}
上面這種方法是可以的。指定指定contentType為application/json是不是也可以呢
var postdata = { ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" };
$.ajax({
type: "post",
url: "http://localhost:27221/api/Charging/SaveData",
contentType: 'application/json',
data: JSON.stringify(postdata),
success: function (data, status) {}
});
[HttpPost]
public bool SaveData(TB_CHARGING lstCharging)
{
return true;
}
(2)實(shí)體和基礎(chǔ)類型一起作為參數(shù)傳遞
var postdata = { ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" };
$.ajax({
type: "post",
url: "http://localhost:27221/api/Charging/SaveData",
contentType: 'application/json',
data: JSON.stringify({ NAME:"Lilei", Charging:postdata }),
success: function (data, status) {}
});
[HttpPost]
public object SaveData(dynamic obj)
{
var strName = Convert.ToString(obj.NAME);
var oCharging = Newtonsoft.Json.JsonConvert.DeserializeObject<TB_CHARGING>(Convert.ToString(obj.Charging));
return strName;
}
3、數(shù)組作為參數(shù)
(1)基礎(chǔ)類型數(shù)組
var arr = ["1", "2", "3", "4"];
$.ajax({
type: "post",
url: "http://localhost:27221/api/Charging/SaveData",
contentType: 'application/json',
data: JSON.stringify(arr),
success: function (data, status) { }
});
[HttpPost]
public bool SaveData(string[] ids)
{
return true;
}
(2)實(shí)體集合
var arr = [
{ ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" },
{ ID: "2", NAME: "Lilei", CREATETIME: "1990-12-11" },
{ ID: "3", NAME: "Lucy", CREATETIME: "1986-01-10" }
];
$.ajax({
type: "post",
url: "http://localhost:27221/api/Charging/SaveData",
contentType: 'application/json',
data: JSON.stringify(arr),
success: function (data, status) {}
});
[HttpPost]
public bool SaveData(List<TB_CHARGING> lstCharging)
{
return true;
}
4、后臺(tái)發(fā)送請(qǐng)求參數(shù)的傳遞
都是通過前端的ajax請(qǐng)求去做的,我們知道,如果調(diào)用方不是web項(xiàng)目,比如Android客戶端,可能需要從后臺(tái)發(fā)送http請(qǐng)求來調(diào)用我們的接口方法。
public void TestReques()
{
//請(qǐng)求路徑
string url = "http://localhost:27221/api/Charging/SaveData";
//定義request并設(shè)置request的路徑
WebRequest request = WebRequest.Create(url);
request.Method = "post";
//初始化request參數(shù)
string postData = "{ ID: \"1\", NAME: \"Jim\", CREATETIME: \"1988-09-11\" }";
//設(shè)置參數(shù)的編碼格式,解決中文亂碼
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
//設(shè)置request的MIME類型及內(nèi)容長度
request.ContentType = "application/json";
request.ContentLength = byteArray.Length;
//打開request字符流
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
//定義response為前面的request響應(yīng)
WebResponse response = request.GetResponse();
//獲取相應(yīng)的狀態(tài)代碼
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
//定義response字符流
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();//讀取所有
Console.WriteLine(responseFromServer);
}
三、put請(qǐng)求
WebApi里面put請(qǐng)求一般用于對(duì)象的更新。它和用法和post請(qǐng)求基本相同。同樣支持[FromBody],同樣可以使用dynamic。
1、基礎(chǔ)類型參數(shù)
$.ajax({
type: "put",
url: "http://localhost:27221/api/Charging/Update",
contentType: 'application/json',
data: JSON.stringify({ ID: "1" }),
success: function (data, status) {}
});
[HttpPut]
public bool Update(dynamic obj )
{
return true;
}
2、實(shí)體作為參數(shù)
和post請(qǐng)求相同。
四、delete請(qǐng)求
參數(shù)傳遞機(jī)制和post也是基本相同。
var arr = [
{ ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" },
{ ID: "2", NAME: "Lilei", CREATETIME: "1990-12-11" },
{ ID: "3", NAME: "Lucy", CREATETIME: "1986-01-10" }
];
$.ajax({
type: "delete",
url: "http://localhost:27221/api/Charging/OptDelete",
contentType: 'application/json',
data: JSON.stringify(arr),
success: function (data, status) {}
});
[HttpDelete]
public bool OptDelete(List<TB_CHARGING> lstChargin)
{
return true;
}
五、總結(jié)
以上比較詳細(xì)的總結(jié)了WebApi各種請(qǐng)求的各種參數(shù)傳遞