下面通過幾個示例看看我們的get請求參數傳遞。
get請求的數據會附在URL之后(就是把數據放置在HTTP協議頭中),而post請求則是放在http協議包的包體中。
1.基礎類型參數
[HttpPost]public bool SaveData([FromBody]string NAME){ return true;}$.Ajax({ type: "post", url: "http://localhost:27221/api/Charging/SaveData", data: { "": "Jim" }, success: function (data, status) {} });2.實體類型參數public class TB_CHARGING { /// <summary> /// 主鍵Id /// </summary> public string ID { get; set; } /// <summary> /// 充電設備名稱 /// </summary> public string NAME { get; set; } /// <summary> /// 充電設備描述 /// </summary> public string DES { get; set; } /// <summary> /// 創建時間 /// </summary> public DateTime CREATETIME { get; set; } }[HttpPost] public bool SaveData(TB_CHARGING oData) { return true; }$.ajax({ type: "post", url: "http://localhost:27221/api/Charging/SaveData", contentType: 'application/json', data: JSON.stringify({ NAME: "Jim",DES:"備注" }), success: function (data, status) {} });3.實體集合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.后臺發送請求參數的傳遞public void TestReques() { //請求路徑 string url = "http://localhost:27221/api/Charging/SaveData"; //定義request并設置request的路徑 WebRequest request = WebRequest.Create(url); request.Method = "post"; //初始化request參數 string postData = "{ ID: /"1/", NAME: /"Jim/", CREATETIME: /"1988-09-11/" }"; //設置參數的編碼格式,解決中文亂碼 byte[] byteArray = Encoding.UTF8.GetBytes(postData); //設置request的MIME類型及內容長度 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(); //獲取相應的狀態代碼 Console.WriteLine(((HttpWebResponse)response).StatusDescription); //定義response字符流 dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string responseFromServer = reader.ReadToEnd();//讀取所有 Console.WriteLine(responseFromServer); }
新聞熱點
疑難解答