c# WPF客户端调用WebAPI并转换成List

时间:2021-08-12 13:30:33

利用HttpClient、JsonConvert实现。

引用Newtonsoft.Json.dll和System.Net.Http。

举个例子:从webapi中获取设备列表。

 public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var list= GetEquipList<EquipModel>(1);
        }

        public List<T> GetEquipList<T>(int orgId)
        {
            string url = "http://127.0.0.1/K3Cloud/BAH.TEST.APP.PCService.EquipService.GetEquipList,BAH.TEST.APP.common.kdsvc";
            var content = new FormUrlEncodedContent(new Dictionary<string, string>()
                {
                        { "orgId",orgId.ToString()}
                 });

            var resultRpt = ExecuteInterfaceByUrl(url, content);
            return JsonConvert.DeserializeObject<IEnumerable<T>>(resultRpt).ToList();

        }

        protected string ExecuteInterfaceByUrl(string url, FormUrlEncodedContent para)
        {
            var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };

            using (var http = new HttpClient(handler))
            {
                var responseRpt = http.PostAsync(url, para).Result;
                var resultRpt = responseRpt.Content.ReadAsStringAsync().Result;

                return resultRpt;
            }
        }
    }
    public class EquipModel
    {
        public string FName { get; set; }
    }

EquipModel是实体类,用来转换Json的,一般和Json格式一样。

ExecuteInterfaceByUrl方法可以做成通用的方法,传入webapi的地址和参数。