首页 > 代码库 > WinForm 对Web Api 增 册 改 查 的基本操作

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 =http://www.mamicode.com/ 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);            }        }

技术分享

 

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