本篇通過get损离、post哥艇、put岸售、delete四種請求方式分別談談基礎類型(包括int/string/datetime等)职烧、實體、數(shù)組等類型的參數(shù)如何傳遞别厘。
一怎棱、get請求
1哩俭、基礎類型參數(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ù)
如果我們在get請求時想將實體對象做參數(shù)直接傳遞到后臺,這樣是不可行的拳恋。原來凡资,get請求的時候,默認是將參數(shù)全部放到了url里面直接以string的形式傳遞的谬运,后臺自然接不到了隙赁。
正確傳參方式:
$.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請求不建議將數(shù)組作為參數(shù)梆暖,因為我們知道get請求傳遞參數(shù)的大小是有限制的伞访,最大1024字節(jié),數(shù)組里面內(nèi)容較多時轰驳,將其作為參數(shù)傳遞可能會發(fā)生參數(shù)超限丟失的情況厚掷。
4、“怪異”的get請求
為什么會說get請求“怪異”呢级解?我們先來看看下面的兩種寫法對比冒黑。
(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;
}
這是標準寫法,后臺加[HttpGet]勤哗,參數(shù)正常得到抡爹。
為了對比,我將[HttpGet]去掉芒划,然后再調(diào)用
//[HttpGet]
public string GetByModel(string strQuery)
{
TB_CHARGING oData = Newtonsoft.Json.JsonConvert.DeserializeObject<TB_CHARGING>(strQuery);
return "ChargingData" + oData.ID;
}
貌似沒有任何問題冬竟!有人就想欧穴,那是否所有的get請求都可以省略掉[HttpGet]這個標注呢。我們試試便知泵殴。
(2)WebApi的方法名稱不以get開頭
我們把之前的方法名由GetByModel改成FindByModel涮帘,這個再正常不過了,很多人查詢就不想用Get開頭袋狞,還有直接用Query開頭的焚辅。這個有什么關系嗎?
$.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]瘫析,運行起來試試砌梆。
如果這種情況下,再把[HttpGet]注釋掉贬循,數(shù)據(jù)就接收不到了咸包。
最后結論:所有的WebApi方法最好是加上請求的方式([HttpGet]/[HttpPost]/[HttpPut]/[HttpDelete]),不要偷懶杖虾,這樣既能防止類似的錯誤烂瘫,也有利于方法的維護,別人一看就知道這個方法是什么請求奇适。
二坟比、post請求
在WebApi的RESETful風格里面,API服務的增刪改查嚷往,分別對應著http的post/delete/put/get請求葛账。我們下面就來說說post請求參數(shù)的傳遞方式。
1皮仁、基礎類型參數(shù)
(1)傳遞一個參數(shù)
post請求的基礎類型的參數(shù)和get請求有點不一樣籍琳,我們知道get請求的參數(shù)是通過url來傳遞的,而post請求則是通過http的請求體中傳過來的贷祈,WebApi的post請求也需要從http的請求體里面去取參數(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ù)的機制是鍵值對,即某一個key等于某一個value付燥,而這里的FromBody和我們一般通過url取參數(shù)的機制則不同宣谈,它的機制是=value,沒有key的概念键科,并且如果你寫了key(比如你的ajax參數(shù)寫的{NAME:"Jim"})闻丑,后臺反而得到的NAME等于null漩怎。不信你可以試試。
(2)傳遞多個參數(shù)
傳遞多個參數(shù)嗦嗡,使用dynamic是一個很不錯的選擇勋锤。
$.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ù)
(1)單個實體作為參數(shù)
上面我們通過dynamic類型解決了post請求基礎類型數(shù)據(jù)的傳遞問題侥祭,那么當我們需要傳遞一個實體作為參數(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ù)傳遞
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)基礎類型數(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)實體集合
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谈宛、后臺發(fā)送請求參數(shù)的傳遞
都是通過前端的ajax請求去做的,我們知道胎署,如果調(diào)用方不是web項目吆录,比如Android客戶端,可能需要從后臺發(fā)送http請求來調(diào)用我們的接口方法琼牧。
public void TestReques()
{
//請求路徑
string url = "http://localhost:27221/api/Charging/SaveData";
//定義request并設置request的路徑
WebRequest request = WebRequest.Create(url);
request.Method = "post";
//初始化request參數(shù)
string postData = "{ ID: \"1\", NAME: \"Jim\", CREATETIME: \"1988-09-11\" }";
//設置參數(shù)的編碼格式恢筝,解決中文亂碼
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
//設置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響應
WebResponse response = request.GetResponse();
//獲取相應的狀態(tài)代碼
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
//定義response字符流
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();//讀取所有
Console.WriteLine(responseFromServer);
}
三、put請求
WebApi里面put請求一般用于對象的更新巨坊。它和用法和post請求基本相同撬槽。同樣支持[FromBody],同樣可以使用dynamic趾撵。
1侄柔、基礎類型參數(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ù)
和post請求相同鼓寺。
四勋拟、delete請求
參數(shù)傳遞機制和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;
}
五妈候、總結
以上比較詳細的總結了WebApi各種請求的各種參數(shù)傳遞