安裝Web API客戶端庫
右鍵單擊專案,選擇管理 NuGet程式包,選擇聯機選項,選擇全部,在搜尋框中輸入“Microsoft.AspNet.WebApi.Client”,
搜尋結果就是要安裝的類庫,單擊安裝到完成。NuGet會自動新增引用
需要引入的名稱空間:
using System.Net.Http;
using System.Net.Http.Headers;
Get呼叫
HttpClient初始化
HttpClient client = new HttpClient(); client.BaseAddress = new Uri("http://localhost:9000/"); // Add an Accept header for JSON format. // 為JSON格式新增一個Accept報頭 client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync("api/GetEmployees").Result; //轉換為同步方法
response 中可以直接拿到http請求狀態。
if (response.IsSuccessStatusCode) //請求成功 { //從方法名中可以看出是非同步呼叫,取Result後,就變成同步了, var results = response.Content.ReadAsAsync<IEnumerable<Employee>>().Result; foreach (var p in results) { Console.WriteLine("{0}\t{1};\t{2}", p.Name, p.Age, p.Sex); } } else { Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase); }
Post呼叫
using System.Net.Http; using System.Net.Http.Headers; //api 為 http://localhost:8000/Employee/Update //傳入引數 name,age,sex HttpClient client = new HttpClient(); public override bool SendMessage() { client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); var paras= new { name ="", age =10,sex="男" }; try { var response = client.PostAsJsonAsync(" http://localhost:8000/Employee/Update", paras).Result; //如果呼叫失敗,丟擲異常 response.EnsureSuccessStatusCode(); if (response.IsSuccessStatusCode) { var result = response.Content.ReadAsStringAsync(); //result.Result 是一個json字串,解析後就可以拿到呼叫後的返回值 return false; } else { return false; } } catch (Exception ex) { return false; } return true; }
put,和delete方法呼叫同post類似,在此不再介紹。