WebApi系列~經過HttpClient來調用Web Api接口~續~實體參數的傳遞

 

回到目錄php

上一講中介紹了使用HttpClient如何去調用一個標準的Web Api接口,而且咱們知道了Post,Put方法只能有一個FromBody參數,再有多個參數時,上講提到,須要將它封裝成一個對象進行傳遞,而這講主要圍繞這個話題來講,接口層添加一個新類User_Info,用來進行數據傳遞,而客戶端使用網頁ajax和控制檯HttpClient的方式分別進行實現,Follow me!html

下面定義一個複雜類型對象java

   public class User_Info
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Info { get; set; }
    }

下面修改上次的api部分,讓它對這個對象進行操做ajax

    [CorsAttribute("http://localhost:3321")]
    public class RegisterController : ApiController
    {
        public static List<User_Info> Model = new List<User_Info>()
        {
            new User_Info{Id=1,Name="zzl",Info="zzl是樓主"},
            new User_Info{Id=2,Name="zhz",Info="zhz是zzl的兒子"},
            new User_Info{Id=3,Name="zql",Info="zql是zzl的妻子"},
            new User_Info{Id=4,Name="bobo",Info="bobo是zzl的朋友"}
        };

        // GET api/values
        public IEnumerable<User_Info> Get()
        {
            return Model;
        }
        // GET api/values/5
        public User_Info Get(int id)
        {
            var entity = Model.FirstOrDefault(i => i.Id == id);
            return entity;
        }
        // GET api/values/5?leval=1
        public HttpResponseMessage Get(int id, int leval)
        {
            return new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent("<em style='color:red'>成功響應(id,level)</em>", System.Text.Encoding.UTF8, "text/html")
            };
        }
        // POST api/values
        public HttpResponseMessage Post([FromBody]User_Info value)
        {
            Model.Add(new User_Info
            {
                Id = value.Id,
                Info = value.Info,
                Name = value.Name,
            });
            //用戶登錄相關
            return new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent("添加數據成功,用戶ID:" + value.Id, System.Text.Encoding.UTF8, "text/plain")
            };
        }
        // PUT api/values?userid=5
        public HttpResponseMessage Put(int userid, [FromBody]User_Info value)
        {
            var entity = Model.FirstOrDefault(i => i.Id == userid);
            entity.Info = value.Info;
            entity.Name = value.Name;
            return new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent("修改數據成功,主鍵:" + userid + ",對象:" + value.Name)
            };
        }

        // DELETE api/values/5
        public HttpResponseMessage Delete(int id)
        {
            Model.Remove(Model.FirstOrDefault(i => i.Id == id));
            return new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent("刪除數據成功")
            };
        }

而最關鍵的地方仍是在各個客戶端調用的時候,首先,你不能期望客戶端去引用你的程序集,由於,不能平臺沒法實現這種引用(java & c#,js & C#,php & c#),因此,在調用時須要有它們各自的方法,而JS的ajax調用時,直接使用json對象便可,鍵名對象json

實體的屬性,在使用HttpClient時,直接爲FormUrlEncodedContent對象賦一個鍵值對的集合便可,下面分別介紹一下c#

HTML的JS實現api

     $.ajax({
            url: "http://localhost:52824/api/register",
            type: "POST",
            data: { Id: 5, Name: '新來的', Info: '你們好' },//這裏鍵名稱必須爲空,多個參數請傳對象,api端參數名必須爲value
            success: function (data) {
                console.log("post:" + data);
            }
        });

        $.ajax({
            url: "http://localhost:52824/api/register",
            type: "GET",
            success: function (data) {
                for (var i in data) {
                    console.log(data[i].Id + " " + data[i].Name);
                }
            }
        });

結果截圖異步

Console程序中使用HttpClient對象進行實現async

       /// <summary>
        /// HttpClient實現Post請求
        /// </summary>
        static async void dooPost()
        {
            string url = "http://localhost:52824/api/register";
             //設置HttpClientHandler的AutomaticDecompression
            var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
            //建立HttpClient(注意傳入HttpClientHandler)
            using (var http = new HttpClient(handler))
            {
                //使用FormUrlEncodedContent作HttpContent
                var content = new FormUrlEncodedContent(new Dictionary<string, string>()       
                {    {"Id","6"},
                     {"Name","添加zzl"},
                     {"Info", "添加動做"}//鍵名必須爲空
                 });

                //await異步等待迴應

                var response = await http.PostAsync(url, content);
                //確保HTTP成功狀態值
                response.EnsureSuccessStatusCode();
                //await異步讀取最後的JSON(注意此時gzip已經被自動解壓縮了,由於上面的AutomaticDecompression = DecompressionMethods.GZip)
                Console.WriteLine(await response.Content.ReadAsStringAsync());
            }

        }
        /// <summary>
        /// HttpClient實現Get請求
        /// </summary>
        static async void dooGet()
        {
            string url = "http://localhost:52824/api/register?id=1";
            //建立HttpClient(注意傳入HttpClientHandler)
            var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };

            using (var http = new HttpClient(handler))
            {
                //await異步等待迴應
                var response = await http.GetAsync(url);
                //確保HTTP成功狀態值
                response.EnsureSuccessStatusCode();

                //await異步讀取最後的JSON(注意此時gzip已經被自動解壓縮了,由於上面的AutomaticDecompression = DecompressionMethods.GZip)
                Console.WriteLine(await response.Content.ReadAsStringAsync());
            }
        }
        /// <summary>
        /// HttpClient實現Put請求
        /// </summary>
        static async void dooPut()
        {
            var userId = 1;
            string url = "http://localhost:52824/api/register?userid=" + userId;

            //設置HttpClientHandler的AutomaticDecompression
            var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
            //建立HttpClient(注意傳入HttpClientHandler)
            using (var http = new HttpClient(handler))
            {
                //使用FormUrlEncodedContent作HttpContent
                var content = new FormUrlEncodedContent(new Dictionary<string, string>()       
                {
                   {"Name","修改zzl"},
                   {"Info", "Put修改動做"}//鍵名必須爲空
                });

                //await異步等待迴應

                var response = await http.PutAsync(url, content);
                //確保HTTP成功狀態值
                response.EnsureSuccessStatusCode();
                //await異步讀取最後的JSON(注意此時gzip已經被自動解壓縮了,由於上面的AutomaticDecompression = DecompressionMethods.GZip)
                Console.WriteLine(await response.Content.ReadAsStringAsync());
            }

        }

 回到目錄post



原文連接:http://www.cnblogs.com/lori/p/4045633.html

相關文章
相關標籤/搜索