WebApi系列~通過HttpClient來調用Web Api接口~續~實體(ti)參(can)數的(de)傳遞(di)
上一講中介紹了使用HttpClient如何去調用一個標準的Web Api接口,并(bing)且我們知道了Post,Put方法只(zhi)能有一(yi)個FromBody參(can)數(shu),再有多個參(can)數(shu)時,上講提到(dao),需(xu)要(yao)將它封裝(zhuang)成一(yi)個對象進(jin)行傳遞,而這講主(zhu)要(yao)圍繞這個話題來說,接口層添(tian)加一(yi)個新類(lei)User_Info,用來進(jin)行數(shu)據傳遞,而客戶端(duan)使用網頁ajax和(he)控(kong)制臺HttpClient的方式分別進(jin)行實(shi)現(xian),Follow me!
下面定義(yi)一(yi)個復(fu)雜類型對(dui)象
public class User_Info { public int Id { get; set; } public string Name { get; set; } public string Info { get; set; } }
下面修改上次的(de)api部(bu)分,讓它對這個對象(xiang)進(jin)行操(cao)作
[CorsAttribute("//localhost:3321")] public class RegisterController : ApiController { public static List<User_Info> Model = new List<User_Info>() { new User_Info{Id=1,Name="zzl",Info="zzl是樓主(zhu)"}, new User_Info{Id=2,Name="zhz",Info="zhz是zzl的兒子"}, new User_Info{Id=3,Name="zql",Info="zql是zzl的妻子(zi)"}, new User_Info{Id=4,Name="bobo",Info="bobo是zzl的朋(peng)友(you)"} }; // GET api/values public IEnumerable<User_Info> Get() { return Model; } // GET api/values/5 public User_Info Get(int id) { var entity = Model.FirstOrDefault(i => i.Id == id); return entity; } // GET api/values/5?leval=1 public HttpResponseMessage Get(int id, int leval) { return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("<em style='color:red'>成功響(xiang)應(id,level)</em>", System.Text.Encoding.UTF8, "text/html") }; } // POST api/values public HttpResponseMessage Post([FromBody]User_Info value) { Model.Add(new User_Info { Id = value.Id, Info = value.Info, Name = value.Name, }); //用戶登陸相關 return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("添加(jia)數(shu)據成功,用戶ID:" + value.Id, System.Text.Encoding.UTF8, "text/plain") }; } // PUT api/values?userid=5 public HttpResponseMessage Put(int userid, [FromBody]User_Info value) { var entity = Model.FirstOrDefault(i => i.Id == userid); entity.Info = value.Info; entity.Name = value.Name; return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("修改數據成(cheng)功,主鍵(jian):" + userid + ",對(dui)象(xiang):" + value.Name) }; } // DELETE api/values/5 public HttpResponseMessage Delete(int id) { Model.Remove(Model.FirstOrDefault(i => i.Id == id)); return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("刪除數(shu)據成(cheng)功") }; }
而(er)最關鍵的地方還是在各(ge)個(ge)客戶端調用(yong)的時候,首先,你不能(neng)指望(wang)客戶端去引(yin)用(yong)你的程序集,因為,不能(neng)平臺無法實現這種引(yin)用(yong)(java & c#,js & C#,php & c#),所以,在調用(yong)時需要有它們各(ge)自的方法,而(er)JS的ajax調用(yong)時,直接使用(yong)json對象(xiang)即(ji)可,鍵名對象(xiang)
實(shi)體的屬性,在使用HttpClient時(shi),直接為FormUrlEncodedContent對(dui)象賦一(yi)(yi)個鍵值對(dui)的集合即可,下面分(fen)別介紹一(yi)(yi)下
HTML的JS實現
$.ajax({ url: "//localhost:52824/api/register", type: "POST", data: { Id: 5, Name: '新來的', Info: '大家好' },//這里鍵名稱(cheng)必(bi)須為(wei)(wei)空,多個參數請(qing)傳對(dui)象(xiang),api端(duan)參數名必(bi)須為(wei)(wei)value success: function (data) { console.log("post:" + data); } }); $.ajax({ url: "//localhost:52824/api/register", type: "GET", success: function (data) { for (var i in data) { console.log(data[i].Id + " " + data[i].Name); } } });
結果截圖
Console程序中使用HttpClient對象進行實現
/// <summary> /// HttpClient實現Post請(qing)求 /// </summary> static async void dooPost() { string url = "//localhost:52824/api/register"; //設置HttpClientHandler的AutomaticDecompression var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip }; //創建(jian)HttpClient(注意傳入HttpClientHandler) using (var http = new HttpClient(handler)) { //使用(yong)FormUrlEncodedContent做HttpContent var content = new FormUrlEncodedContent(new Dictionary<string, string>() { {"Id","6"}, {"Name","添加zzl"}, {"Info", "添加動作"}//鍵(jian)名必須為空 }); //await異步等待(dai)回(hui)應(ying) var response = await http.PostAsync(url, content); //確(que)保HTTP成功狀態值 response.EnsureSuccessStatusCode(); //await異步讀取最后的JSON(注意(yi)此時(shi)gzip已經被自動(dong)解壓(ya)縮了,因(yin)為(wei)上面的AutomaticDecompression = DecompressionMethods.GZip) Console.WriteLine(await response.Content.ReadAsStringAsync()); } } /// <summary> /// HttpClient實現Get請求 /// </summary> static async void dooGet() { string url = "//localhost:52824/api/register?id=1"; //創建HttpClient(注意傳入HttpClientHandler) var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip }; using (var http = new HttpClient(handler)) { //await異步等(deng)待回(hui)應(ying) var response = await http.GetAsync(url); //確(que)保HTTP成功(gong)狀態(tai)值(zhi) response.EnsureSuccessStatusCode(); //await異步讀(du)取最后的(de)(de)JSON(注意此時gzip已經被(bei)自動解壓縮了,因為上(shang)面(mian)的(de)(de)AutomaticDecompression = DecompressionMethods.GZip) Console.WriteLine(await response.Content.ReadAsStringAsync()); } } /// <summary> /// HttpClient實現Put請(qing)求 /// </summary> static async void dooPut() { var userId = 1; string url = "//localhost:52824/api/register?userid=" + userId; //設置(zhi)HttpClientHandler的AutomaticDecompression var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip }; //創建(jian)HttpClient(注意傳入HttpClientHandler) using (var http = new HttpClient(handler)) { //使用(yong)FormUrlEncodedContent做(zuo)HttpContent var content = new FormUrlEncodedContent(new Dictionary<string, string>() { {"Name","修改zzl"}, {"Info", "Put修改動作"}//鍵名必(bi)須為空 }); //await異(yi)步(bu)等待回應 var response = await http.PutAsync(url, content); //確保(bao)HTTP成功狀態值 response.EnsureSuccessStatusCode(); //await異步讀取最后的(de)JSON(注意(yi)此(ci)時gzip已經被自(zi)動解壓縮了,因為上面的(de)AutomaticDecompression = DecompressionMethods.GZip) Console.WriteLine(await response.Content.ReadAsStringAsync()); } }