首先编写服务端
数据模型
public class School { public int ID { get; set; } public string Subject { get; set; } public string Teacher { get; set; } }
然后控制器
public class ClassController : ApiController { School[] school = new School[] { new School{ID = 0, Subject = "数学", Teacher ="王"}, new School{ID = 1, Subject = "哲学", Teacher = "李"}, new School{ID = 2, Subject = "计算机", Teacher = "张"} };
//为了简单只实现一个功能 public IEnumerable<School> GetAllSchool(){ return school; } }
客户端:新建一个控制台。首先-〉库程序安装一个Microsoft.AspNet.WebApi.Client
static void Main(string[] args) { HttpClient client = new HttpClient();
//设置Uri client.BaseAddress = new Uri("http://localhost:14490/");
//HTTP请求Accept标头 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //异步将get请求发送给指定Uri HttpResponseMessage response = client.GetAsync("api/class").Result; if(response.IsSuccessStatusCode){
//获取HTTP请求内容 var products = response.Content.ReadAsAsync<IEnumerable<School>>().Result; foreach(var p in products){ Console.WriteLine("{0}:{1}--{2}",p.ID,p.Subject,p.Teacher); } } Console.ReadKey(); }
public class School { public int ID { get; set; } public string Subject { get; set; } public string Teacher { get; set; } }
最后的结果