asp.net web api定义的c/s调用方法一例

asp.net web api定义的c/s调用方法一例

using Common;
using Newtonsoft.Json.Linq;
using SapAuthorizationWebAPI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            //Process_selfhost();

            //Process_webapi_get();     //OK

            //Process_webapi_post();    //OK

            //Process_webapi_delete();  //OK

            Process_webapi_put();       //OK
            //
            Console.Read();
        }
        private async static void Process_selfhost()
        {            
            HttpClient httpClient = new HttpClient();
            //获取当前联系人列表 get模式   OK
            HttpResponseMessage response = await httpClient.GetAsync("http://localhost/selfhost/api/contacts");
            IEnumerable<Contact> contacts = await response.Content.ReadAsAsync<IEnumerable<Contact>>();
            Console.WriteLine("当前联系人列表:");
            ListContacts(contacts);
            //添加新的联系人     post模式   OK
            Contact c = new Contact{Name="王五",PhoneNo="0512-34567890",EmailAddress="[email protected]"};
            await httpClient.PostAsJsonAsync<Contact>("http://localhost/selfhost/api/contacts", c);
            Console.WriteLine("添加新联系人 王五 :");
            response = await httpClient.GetAsync("http://localhost/selfhost/api/contacts");
            contacts = await response.Content.ReadAsAsync<IEnumerable<Contact>>();
            ListContacts(contacts);
            //修改现有的某个联系人  get  put模式 selfhost OK
            response = await httpClient.GetAsync("http://localhost/selfhost/api/contacts/001");
            c = (await response.Content.ReadAsAsync<IEnumerable<Contact>>()).First();
            c.Name = "赵六";
            c.EmailAddress = "[email protected]";
            await httpClient.PutAsJsonAsync<Contact>("http://localhost/selfhost/api/contacts/001", c);
            Console.WriteLine("修改联系人001信息:");
            response = await httpClient.GetAsync("http://localhost/selfhost/api/contacts");
            contacts = await response.Content.ReadAsAsync<IEnumerable<Contact>>();
            ListContacts(contacts);
            //删除现有的某个联系人  delete  selfhost模式  OK
            await httpClient.DeleteAsync("http://localhost/selfhost/api/contacts/002");
            Console.WriteLine("删除联系人002:");
            response = await httpClient.GetAsync("http://localhost/selfhost/api/contacts");
            contacts = await response.Content.ReadAsAsync<IEnumerable<Contact>>();
            ListContacts(contacts);
        }
        private static void ListContacts(IEnumerable<Contact> contacts)
        {
            foreach (Contact c in contacts)
            {
                Console.WriteLine("{0,-6}{1,-6}{2,-20}{3,-10}",c.Id,c.Name,c.EmailAddress,c.PhoneNo);
            }
            Console.WriteLine();
        }
        //OK get
        private async static void Process_webapi_get()
        {
            HttpClient httpClient = new HttpClient();
            //获取当前联系人列表 get模式   OK
            var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
            using (var http = new HttpClient(handler))
            {
                var response = await http.GetAsync("http://localhost:15468/api/account/login/hsg/hsg");
                string JsonMsg = await response.Content.ReadAsStringAsync();
                Console.WriteLine(JsonMsg);
                //
                JObject jsonObj = JObject.Parse(JsonMsg);
                string isOk = jsonObj["isOk"].ToString();
                string msg = jsonObj["message"].ToString();
                //
                JObject jsonData = JObject.Parse(jsonObj["data"].ToString());
                string id = jsonData["ID"].ToString();
                string CNNAME = jsonData["CNNAME"].ToString();
                Console.WriteLine(id);
                //
                SapHttpActionResult2 ar = ObjectUtil.Deserialize<SapHttpActionResult2>(JsonMsg);
                Console.WriteLine("get反序列化结果:"+ar.message);
            }
        }
        //OK post
        private async static void Process_webapi_post()
        {
            HttpClient httpClient = new HttpClient();
            //获取当前联系人列表 get模式   OK
            var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
            using (var http = new HttpClient(handler))
            {
                //var content = new FormUrlEncodedContent(new Dictionary<string, string>()
                //{
                //    {"account","hsg" },
                //    {"new_pwd","123456" },
                //    {"old_pwd","hsg" }
                //});
                string url = "http://localhost:15468/api/user/ModifyPassword/hsg/123456/hsg";
                var response = await http.PostAsync(url, null);
                //确保HTTP成功状态值
                response.EnsureSuccessStatusCode();
                //
                string JsonMsg = await response.Content.ReadAsStringAsync();
                Console.WriteLine(JsonMsg);
                //
                JObject jsonObj = JObject.Parse(JsonMsg);
                string isOk = jsonObj["isOk"].ToString();
                string msg = jsonObj["message"].ToString();
                //
                SapHttpActionResult2 ar = ObjectUtil.Deserialize<SapHttpActionResult2>(JsonMsg);
                Console.WriteLine("post反序列化结果:" + ar.message);
            }
        }

        //OK  delete  删除用户 DELETE /api/user/DelteUser/{id}
        private async static void Process_webapi_delete()
        {
            HttpClient httpClient = new HttpClient();
            //模式   OK
            var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
            using (var http = new HttpClient(handler))
            {
                //var content = new FormUrlEncodedContent(new Dictionary<string, string>()
                //{
                //    {"account","hsg" },
                //    {"new_pwd","123456" },
                //    {"old_pwd","hsg" }
                //});
                string url = "http://localhost:15468/api/user/DelteUser/121212";
                var response = await http.DeleteAsync(url);
                //确保HTTP成功状态值
                response.EnsureSuccessStatusCode();
                //
                string JsonMsg = await response.Content.ReadAsStringAsync();
                Console.WriteLine(JsonMsg);
                //
                JObject jsonObj = JObject.Parse(JsonMsg);
                string isOk = jsonObj["isOk"].ToString();
                string msg = jsonObj["message"].ToString();
                //
                SapHttpActionResult2 ar = ObjectUtil.Deserialize<SapHttpActionResult2>(JsonMsg);
                Console.WriteLine("delete反序列化结果:" + ar.message);
            }
        }
        //OK  put  修改用户 put api/PutUser/{id}
        private async static void Process_webapi_put()
        {
            HttpClient httpClient = new HttpClient();
            //模式   OK
            var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
            using (var http = new HttpClient(handler))
            {
                var content = new FormUrlEncodedContent(new Dictionary<string, string>()
                {
                    {"ID","121212121" },
                    {"Caption","hsg" },
                    {"ClientID","ClientID_12121" }
                });
                //修改用户 put api/PutUser/{id}
                string url = "http://localhost:15468/api/user/PutUser/121212";
                var response = await http.PutAsync(url, content);
                //确保HTTP成功状态值
                response.EnsureSuccessStatusCode();
                //
                string JsonMsg = await response.Content.ReadAsStringAsync();
                Console.WriteLine(JsonMsg);
                //
                JObject jsonObj = JObject.Parse(JsonMsg);
                string isOk = jsonObj["isOk"].ToString();
                string msg = jsonObj["message"].ToString();
                //
                SapHttpActionResult2 ar = ObjectUtil.Deserialize<SapHttpActionResult2>(JsonMsg);
                Console.WriteLine("put反序列化结果:" + ar.message);
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/hsg77/article/details/80294124