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

    最后的结果

  • 相关阅读:
    PyQt5-QComboBox控件使用
    PyQt5-按钮控件使用
    PyQt5-QTextEdit控件使用
    Ubuntu12.04下YouCompleteMe安装教程(部分)
    ubuntu下vim的简单配置
    VirtualBox下vim无法正常使用问题解决
    树莓派下ubuntu-mate中ssh服务的安装与开机后自启动
    水仙花小游戏
    C语言实现判断分数等级
    临时记录(不断更新)
  • 原文地址:https://www.cnblogs.com/richy/p/2860872.html
Copyright © 2011-2022 走看看