1.通過路由接收參數,一般直接通過Url拼接直接匹配路由對應參數
這個直接通過設置路由,然后Url的位置對應即可;
2.通過QueryString傳遞參數
一般常見於Get訪問數據傳參;
3.通過[FromBody]直接在形參接收數據
客戶端代碼:
private async void Btn_SendData_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(TB_SendDataUrl.Text)) return; HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(TB_SendDataUrl.Text); //request.ContentType = "application/x-www-form-urlencoded";//post發送數據必須使用這個標頭才能被webapi [frombody]接收 request.ContentType = "application/json"; //如果用了newtonsoft json 轉換數據,那么必須用此標頭,否則服務器將無法解析數據 request.Method = "post"; //發送的數據 List<Person> listP = new List<Person>(); Person p1 = new Person { ID = 1, Name = "張三", Age = 27 }; Person p2 = new Person { ID = 2, Name = "李四", Age = 25 }; Person p3 = new Person { ID = 3, Name = "王五", Age = 28 }; listP.Add(p1); listP.Add(p2); listP.Add(p3); byte[] byteArray; Person p = new Person { ID = 1, Name = "張三", Age = 27 }; //byteArray = Encoding.UTF8.GetBytes(ParseToString(p)); string data = await JsonConvert.SerializeObjectAsync(listP);//直接序列化比上一行代碼 更方便 byteArray = Encoding.UTF8.GetBytes(data);//對數據進行轉碼,可以將中文數據進行傳輸 request.ContentLength = byteArray.Length; Stream reqStream = await request.GetRequestStreamAsync(); reqStream.Write(byteArray,0,byteArray.Length); reqStream.Close(); string responseFromServer = string.Empty; WebResponse response = await request.GetResponseAsync(); using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { responseFromServer = reader.ReadToEnd(); } if(string.IsNullOrEmpty(responseFromServer)) { TB_SendResponseData.Text = "NULL"; } else { TB_SendResponseData.Text = responseFromServer; List<Person> resData = JsonConvert.DeserializeObject<List<Person>>(responseFromServer); } response.Close(); }
這里注意如果使用Newtonsoft將傳輸數據轉換成了json,需要將contenttype設置為"application/json",這里十分關鍵,如果不是這個表頭,服務端將不能正確解析數據
服務端代碼:
[HttpPost] public List<Person> SendListData([FromBody] List<Person> listP) { return listP; }
4.通過 解析Request.Content 中的請求消息實體得到數據,這種一般是通過Post上傳的數據
[HttpPost] public async Task<List<Person>> SendListJsontData() { List<Person> data = await this.Request.Content.ReadAsAsync<List<Person>>(); return data; }
由於Task是4.5以上框架引入的,也可以在4.5以下框架中寫成非異步調用的方式:
[HttpPost] public string PostNewData() { var t = this.Request.Content.ReadAsStringAsync(); string data = t.Result; return data; }
前台使用的代碼(推薦):
public static string HttpPost(string url, string PostData) { Encoding encoding = Encoding.UTF8; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.Accept = "text/html, application/xhtml+xml, */*"; //這里只有使用var data = HttpContext.Current.Request.Form["Name"].ToString();才切換到表單 //如果api使用Request.Content.ReadAsStringAsync();則無所謂切換 request.ContentType = "application/x-www-form-urlencoded ";//根據服務端進行 切換 //request.ContentType = "application/json; charset=utf-8 "; byte[] buffer = encoding.GetBytes(PostData); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { return reader.ReadToEnd(); } }
主函數調用
static void Main(string[] args) {
string url = "http://localhost:50041/api/Home/PostNewData"; //string data = "Name="; //for (int i = 0; i < 1000; i++) //{ // data += Guid.NewGuid().ToString() + ";"; //} string data = "Id=9527&Name=zhangSan&Category=A8&Price=88"; string res = HttpPost(url, data); Console.WriteLine($"結果:{res}"); Console.ReadKey(); }
使用.Net內置的方法即可讀到傳輸數據。