目前所了解的请求WebAPI的方式有通过后台访问api 和通过js 直接访问api接口
首先介绍下通过后台访问api的方法,可以使用HttpClient的方式也可以使用WebRequest的方式
1、HttpClient的方式
(1)Get请求
string url = "http://10.1.1.1:8080/"; public ActionResult GetAll() { HttpClient client = new HttpClient(); client.BaseAddress = new Uri(url); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = client.GetAsync("api/goods/getlist?pageindex=0&pagesize=10").Result; // Blocking call(阻塞调用)! var result = ""; if (response.IsSuccessStatusCode) { result = response.Content.ReadAsStringAsync().Result; JavaScriptSerializer Serializer = new JavaScriptSerializer(); var items = Serializer.DeserializeObject(result); return Json(items); } else { return Json(result); } }