• WinForm 对Web Api 增 册 改 查 的基本操作


    WebApi代码:

     public class ValuesController : ApiController
        {
         
              Entities db=new Entities();
       
            // GET api/values
            public IEnumerable<Person> Get()
            {
                return  db.Person;
            }
    
            // GET api/values/5
            public Person Get(int id)
            {
                return db.Person.FirstOrDefault(o => o.id == id);
            }
    
            // POST api/values
            public void Post([FromBody]Person value)
            {
                // People peple =(People) JsonConvert.DeserializeObject(value);
                if (db.Person.FirstOrDefault(o => o.id == value.id) == null)
                {
                    db.Person.Add(value); 
                }
                db.SaveChanges();
            }
    
            // PUT api/values/5
            public void Put(int id, [FromBody]Person value)
            {
                var query = db.Person.FirstOrDefault(o => o.id == id);
                if (query != null)
                {
                    query.Name = value.Name;
                }
                db.SaveChanges();
            }
    
            // DELETE api/values/5
            public void Delete(int id)
            {
                var query = db.Person.FirstOrDefault(o => o.id == id);
                if (query != null)
                {
                    db.Person.Remove(query);
                    db.SaveChanges();
                }
              
               
            }
        }

    Winform的基本代码:

     private Uri url = new Uri("http://localhost:18827/api/values");
    
     /// <summary>
            ////// </summary>
            private async void button1_Click(object sender, EventArgs e)
            {
                People people = new People();
                people.Id = new Random().Next(100, 9999999);
                people.Name = "" + people.Id;
                string data = JsonConvert.SerializeObject(people);
    
                //创建一个处理序列化的DataContractJsonSerializer
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(People));
                MemoryStream ms = new MemoryStream();
                serializer.WriteObject(ms, people);
                //一定要在这设定Position
                ms.Position = 0;
                HttpContent content = new StreamContent(ms);//将MemoryStream转成HttpContent
                //一定要设定Header
                content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                HttpClient client = new HttpClient();
                //由HttpClient发出Post Method
                HttpResponseMessage response = await client.PostAsync(url, content);
    
                if (response.IsSuccessStatusCode)
                {
    
                }
                else
                {
    
                }
    
    
    
            }
    
            /// <summary>
            /// 删除
            /// </summary>
            private async void button2_Click(object sender, EventArgs e)
            {
                    HttpClient client = new HttpClient();
                    //由HttpClient发出Delete Method
                    HttpResponseMessage response = await client.DeleteAsync(url +"/1");
                    if (response.IsSuccessStatusCode)
                    {
                        MessageBox.Show("成功");
                    }
            }
    
            //修改
            private async void button3_Click(object sender, EventArgs e)
            {
                //创建一个处理序列化的DataContractJsonSerializer
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(People));
                MemoryStream ms = new MemoryStream();
                //将资料写入MemoryStream
                serializer.WriteObject(ms, new People() { Id = 1, Name = "Hello ni" });
                //一定要在这设定Position
                ms.Position = 0;
                HttpContent content = new StreamContent(ms);//将MemoryStream转成HttpContent
                content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                HttpClient client = new HttpClient();
               //由HttpClient发出Put Method
                HttpResponseMessage response = await client.PutAsync(url + "/1", content);
                if (response.IsSuccessStatusCode)
                {
                    MessageBox.Show("成功");
                }
            }
    
            /// <summary>
            /// 获取所有
            /// </summary>
            private void button4_Click(object sender, EventArgs e)
            {
                using (WebClient client = new WebClient())
                {
                    client.Headers["Type"] = "GET";
                    client.Headers["Accept"] = "application/json";
                    client.Encoding = Encoding.UTF8;
                    client.DownloadStringCompleted += (senderobj, es) =>
                    {
                        if (es.Result != null)
                        {
                            var test = JsonConvert.DeserializeObject<People[]>(es.Result);
                            dataGridView1.DataSource = test;
                        }
                    };
                    client.DownloadStringAsync(url);
    
    
                }
            }

  • 相关阅读:
    HTML5 WebAudioAPI-实例(二)
    HTML5 WebAudioAPI简介(一)
    HTML5 <Audio/>标签Api整理(二)
    HTML5 <Audio>标签API整理(一)
    CSS3 box-sizing 属性
    CSS3新增Hsl、Hsla、Rgba色彩模式以及透明属性(转)
    CSS3 颜色值HSL表示方式&简单实例
    C#使用Process类调用外部程序(转)
    乐视手机查看运行内存方法、EUI(Eco User Interface)乐视系统查看手机运行内存方法
    HTML5媒体播放说明
  • 原文地址:https://www.cnblogs.com/w2011/p/4228774.html
Copyright © 2020-2023  润新知