通过HttpClient来调用Web Api接口~续~实体参数的传递
生活随笔
收集整理的這篇文章主要介紹了
通过HttpClient来调用Web Api接口~续~实体参数的传递
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
并且我們知道了Post,Put方法只能有一個FromBody參數(shù),再有多個參數(shù)時,上講提到,需要將它封裝成一個對象進行傳遞,而這講主要圍繞這個話題來說,接口層添加一個新類User_Info,用來進行數(shù)據(jù)傳遞,而客戶端使用網(wǎng)頁ajax和控制臺HttpClient的方式分別進行實現(xiàn),Follow me!
下面定義一個復(fù)雜類型對象
public class User_Info{public int Id { get; set; }public string Name { get; set; }public string Info { get; set; }}下面修改上次的api部分,讓它對這個對象進行操作
[CorsAttribute("http://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是樓主"},new User_Info{Id=2,Name="zhz",Info="zhz是zzl的兒子"},new User_Info{Id=3,Name="zql",Info="zql是zzl的妻子"},new User_Info{Id=4,Name="bobo",Info="bobo是zzl的朋友"}};// GET api/valuespublic IEnumerable<User_Info> Get(){return Model;}// GET api/values/5public User_Info Get(int id){var entity = Model.FirstOrDefault(i => i.Id == id);return entity;}// GET api/values/5?leval=1public HttpResponseMessage Get(int id, int leval){return new HttpResponseMessage(HttpStatusCode.OK){Content = new StringContent("<em style='color:red'>成功響應(yīng)(id,level)</em>", System.Text.Encoding.UTF8, "text/html")};}// POST api/valuespublic HttpResponseMessage Post([FromBody]User_Info value){Model.Add(new User_Info{Id = value.Id,Info = value.Info,Name = value.Name,});//用戶登陸相關(guān)return new HttpResponseMessage(HttpStatusCode.OK){Content = new StringContent("添加數(shù)據(jù)成功,用戶ID:" + value.Id, System.Text.Encoding.UTF8, "text/plain")};}// PUT api/values?userid=5public 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("修改數(shù)據(jù)成功,主鍵:" + userid + ",對象:" + value.Name)};}// DELETE api/values/5public HttpResponseMessage Delete(int id){Model.Remove(Model.FirstOrDefault(i => i.Id == id));return new HttpResponseMessage(HttpStatusCode.OK){Content = new StringContent("刪除數(shù)據(jù)成功")};}而最關(guān)鍵的地方還是在各個客戶端調(diào)用的時候,首先,你不能指望客戶端去引用你的程序集,因為,不能平臺無法實現(xiàn)這種引用(java & c#,js & C#,php & c#),所以,在調(diào)用時需要有它們各自的方法,而JS的ajax調(diào)用時,直接使用json對象即可,鍵名對象
實體的屬性,在使用HttpClient時,直接為FormUrlEncodedContent對象賦一個鍵值對的集合即可,下面分別介紹一下
HTML的JS實現(xiàn)
$.ajax({url: "http://localhost:52824/api/register",type: "POST",data: { Id: 5, Name: '新來的', Info: '大家好' },//這里鍵名稱必須為空,多個參數(shù)請傳對象,api端參數(shù)名必須為valuesuccess: function (data) {console.log("post:" + data);}});$.ajax({url: "http://localhost:52824/api/register",type: "GET",success: function (data) {for (var i in data) {console.log(data[i].Id + " " + data[i].Name);}}});結(jié)果截圖
Console程序中使用HttpClient對象進行實現(xiàn)
/// <summary>/// HttpClient實現(xiàn)Post請求/// </summary>static async void dooPost(){string url = "http://localhost:52824/api/register";//設(shè)置HttpClientHandler的AutomaticDecompressionvar handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };//創(chuàng)建HttpClient(注意傳入HttpClientHandler)using (var http = new HttpClient(handler)){//使用FormUrlEncodedContent做HttpContentvar content = new FormUrlEncodedContent(new Dictionary<string, string>() { {"Id","6"},{"Name","添加zzl"},{"Info", "添加動作"}//鍵名必須為空});//await異步等待回應(yīng)var response = await http.PostAsync(url, content);//確保HTTP成功狀態(tài)值response.EnsureSuccessStatusCode();//await異步讀取最后的JSON(注意此時gzip已經(jīng)被自動解壓縮了,因為上面的AutomaticDecompression = DecompressionMethods.GZip)Console.WriteLine(await response.Content.ReadAsStringAsync());}}/// <summary>/// HttpClient實現(xiàn)Get請求/// </summary>static async void dooGet(){string url = "http://localhost:52824/api/register?id=1";//創(chuàng)建HttpClient(注意傳入HttpClientHandler)var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };using (var http = new HttpClient(handler)){//await異步等待回應(yīng)var response = await http.GetAsync(url);//確保HTTP成功狀態(tài)值response.EnsureSuccessStatusCode();//await異步讀取最后的JSON(注意此時gzip已經(jīng)被自動解壓縮了,因為上面的AutomaticDecompression = DecompressionMethods.GZip)Console.WriteLine(await response.Content.ReadAsStringAsync());}}/// <summary>/// HttpClient實現(xiàn)Put請求/// </summary>static async void dooPut(){var userId = 1;string url = "http://localhost:52824/api/register?userid=" + userId;//設(shè)置HttpClientHandler的AutomaticDecompressionvar handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };//創(chuàng)建HttpClient(注意傳入HttpClientHandler)using (var http = new HttpClient(handler)){//使用FormUrlEncodedContent做HttpContentvar content = new FormUrlEncodedContent(new Dictionary<string, string>() {{"Name","修改zzl"},{"Info", "Put修改動作"}//鍵名必須為空});//await異步等待回應(yīng)var response = await http.PutAsync(url, content);//確保HTTP成功狀態(tài)值response.EnsureSuccessStatusCode();//await異步讀取最后的JSON(注意此時gzip已經(jīng)被自動解壓縮了,因為上面的AutomaticDecompression = DecompressionMethods.GZip)Console.WriteLine(await response.Content.ReadAsStringAsync());}} 轉(zhuǎn):http://www.cnblogs.com/lori/p/4045633.html總結(jié)
以上是生活随笔為你收集整理的通过HttpClient来调用Web Api接口~续~实体参数的传递的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在WebApi中实现Cors访问
- 下一篇: 我个人房子卖给寺庙用缴税吗?