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

    最后的结果

  • 相关阅读:
    Linux_LEMP
    Linux_LEMP
    Linux_指令杂烩
    Linux_指令杂烩
    Linux_SELinux使用
    AWS S3存储基于Hadoop之上的一致性保证
    Ozone数据写入过程分析
    Ozone Datanode的分布式元数据管理
    聊聊Ozone的Topology Awareness
    Ozone数据探查服务Recon的启用
  • 原文地址:https://www.cnblogs.com/richy/p/2860872.html
Copyright © 2011-2022 走看看