zoukankan      html  css  js  c++  java
  • .net 客户端使用asp.net web api

    首先编写服务端

    数据模型

     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; } }

    最后的结果

  • 相关阅读:
    LeetCode_222.完全二叉树的节点个数
    LeetCode_219.存在重复元素 II
    LeetCode_217.存在重复元素
    LeetCode_215.数组中的第K个最大元素
    LeetCode_21.合并两个有序链表
    LeetCode_206.反转链表
    LeetCode_205.同构字符串
    LeetCode_202.快乐数
    LeetCode_20.有效的括号
    LeetCode_2.两数相加
  • 原文地址:https://www.cnblogs.com/richy/p/2860872.html
Copyright © 2011-2022 走看看