c # WPF client calls and converted into WebAPI List

Original: c # WPF client calls and converted into WebAPI List

Use HttpClient, JsonConvert achieve.

References Newtonsoft.Json.dll and System.Net.Http.

For example: a list acquisition device from the 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 entity class, for converting the Json, the same general format and Json.

ExecuteInterfaceByUrl method can be made common method, passing webapi addresses and parameters.

 

Guess you like

Origin www.cnblogs.com/lonelyxmas/p/11112132.html