不囉說直接進入正題,先記錄Get的用法,Post 跟Put目前還撞鬼等待解決中
我用預設的WebApi範例
Api端
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Net;
5: using System.Net.Http;
6: using System.Web.Http;
7:
8: namespace WebApiTest.Controllers
9: {
10: public class APITestController : ApiController
11: {
12: // GET api/apitest
13: public IEnumerable<string> Get()
14: {
15: return new string[] { "value1", "value2" };
16: }
17:
18: // GET api/apitest/5
19: public string Get(int id)
20: {
21: return "value";
22: }
23:
24: // POST api/apitest
25: public string Post([FromBody]string value)
26: {
27: return "ok";
28: }
29:
30: // PUT api/apitest/5
31: public void Put(int id, [FromBody]string value)
32: {
33: }
34:
35: // DELETE api/apitest/5
36: public void Delete(int id)
37: {
38: }
39: }
40: }
WinForm端
1: private void button1_Click(object sender, EventArgs e)
2: {
3: string temp = "";
4: var content = new StringContent(log);
5: var address = new Uri("http://localhost:9101/api/" + "apitest/5"); //Api位置
6: var httpClient = new HttpClient();
7: #region get
8: httpClient.GetAsync(address).ContinueWith((requestTask) =>
9: {
10: HttpResponseMessage response = requestTask.Result;
11: response.EnsureSuccessStatusCode();
12: response.Content.ReadAsStringAsync().ContinueWith(
13: (readTask) =>
14: {
15: temp = readTask.Result;
16: });
17: });
18: #endregion
19: Thread.Sleep(1000); //因為不同執行緒所以要睡一下等他拿到資料
20: Add(temp);
21: }
此方法會將讀到的字串解析出來丟到 ListBox 元件裡面。
全站熱搜