1、创建ApiHelper类
2、复制以下代码到类中

using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace 对应的命名空间 { public class ApiHelper { /// <summary> /// api调用方法 /// </summary> /// <param name="controllerName">控制器名称</param> /// <param name="overb">请求方式</param> /// <param name="action">方法名称</param> /// <param name="obj">方法参数</param> /// <returns>json字符串</returns> public static string GetApiMethod(string controllerName, string overb, string action, object obj = null) { Task<HttpResponseMessage> task = null; string json = ""; //创建一个Http客户端对象 HttpClient client = new HttpClient(); //指定访问WebApi的uri地址 client.BaseAddress = new Uri("http://localhost:47369/api/" + controllerName + "/"); /*根据不同的动作执行不同的方法*/ switch (overb) { case "get": task = client.GetAsync(action); break; case "post": task = client.PostAsJsonAsync(action, obj); break; case "delete": task = client.DeleteAsync(action); break; case "put": task = client.PutAsJsonAsync(action, obj); break; default: break; } //等待请求的过程 task.Wait(); //接收响应的结果 var response = task.Result; //判断响应的状态码是成功时候 if (response.IsSuccessStatusCode) { //从响应对象的内容中读取字符串 var read = response.Content.ReadAsStringAsync(); //等待读取的过程 read.Wait(); //接收读取的结果-json json = read.Result; } return json; } } }
3、修改命名空间
4、成功调用