mjhockstein avatar image
0 Votes"
mjhockstein asked PeterFleischer-3316 commented

What is the correct package to create an HTTP client in a WPF Core3 desktop app?

I have a WPF desktop app using Microsoft.WnidowsDesktop.App.WPF and Microsoft.NETCore.App v3.1. I would like to add an HTTP client for simple GET/POST...

What is the correct package to add an HTTP client so I can accomplish WPF-REST Web API consumption? Per chance is it Microsoft.AspNet.WebApi.Client?

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

PeterFleischer-3316 avatar image
0 Votes"
PeterFleischer-3316 answered PeterFleischer-3316 commented

Hi, you can use System.Net.Http.HttpClient.GetAsync like in following demo. Only NewtonSoft.Json is necessary.

 <Window x:Class="WpfApp1.Window03"
         Title="Window03" Height="450" Width="800">
     <DataGrid Name="DGD_UserList" 
               ItemsSource="{Binding ContentModels}">
         <DataGridTextColumn Binding="{Binding Name}" Header="Object Id" IsReadOnly="True"/>
         <DataGridTextColumn Binding="{Binding ProductUrl}" Header="Continent" IsReadOnly="True"/>

 using Newtonsoft.Json;
 using System;
 using System.Collections.Generic;
 using System.Collections.ObjectModel;
 using System.ComponentModel;
 using System.Net.Http;
 using System.Runtime.CompilerServices;
 using System.Threading;
 using System.Threading.Tasks;
 using System.Windows;
 namespace WpfApp03
   public class ViewModel : INotifyPropertyChanged
     public event PropertyChangedEventHandler PropertyChanged;
     private static string _RootUrl = @"";
     private AsyncObservableCollection<ContentModel> _ContentModels = null;
     public AsyncObservableCollection<ContentModel> ContentModels
       get { return _ContentModels; }
       set { _ContentModels = value; OnPropertyChanged(); }
     public ViewModel() => this.ContentModels = this.GetContentData();
     #region "Read"
     private AsyncObservableCollection<ContentModel> GetContentData()
       AsyncObservableCollection<ContentModel> ReturnContentModles = null;
       Task<AsyncObservableCollection<ContentModel>> ContentTask = this.GetContentModels();
       if (ContentTask.Result.Count > 0) ReturnContentModles = ContentTask.Result;
       return ReturnContentModles;
     private async Task<AsyncObservableCollection<ContentModel>> GetContentModels()
       AsyncObservableCollection<ContentModel> ReturnContinentModels = new AsyncObservableCollection<ContentModel>();
         using (HttpClient httpClient = new HttpClient())
           httpClient.DefaultRequestHeaders.Add("Accept", "application/json;charset=UTF-8");
           using (HttpResponseMessage HttpResponseMessage = await httpClient.GetAsync(string.Concat(_RootUrl, ""), HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false))
             if (HttpResponseMessage.StatusCode == System.Net.HttpStatusCode.OK)
               using (HttpContent HttpContent = HttpResponseMessage.Content)
                 string MyContent = await HttpContent.ReadAsStringAsync();
                 var root = JsonConvert.DeserializeObject<RootObject>(MyContent);
                 ReturnContinentModels = new AsyncObservableCollection<ContentModel>(root.products);
       catch (Exception ex) { Console.WriteLine(ex.Message); }
       return ReturnContinentModels;
     protected void OnPropertyChanged([CallerMemberName] string propertyName = "") =>
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
   public class AsyncObservableCollection<T> : ObservableCollection<T>
     private readonly SynchronizationContext _synchronizationContext = SynchronizationContext.Current;
     public AsyncObservableCollection() { }
     public AsyncObservableCollection(IEnumerable<T> list) : base(list) { }
     private void ExecuteOnSyncContext(Action action)
       if (SynchronizationContext.Current == _synchronizationContext) action();
       else _synchronizationContext.Send(_ => action(), null);
     protected override void InsertItem(int index, T item) => ExecuteOnSyncContext(() => base.InsertItem(index, item));
     protected override void RemoveItem(int index) => ExecuteOnSyncContext(() => base.RemoveItem(index));
     protected override void SetItem(int index, T item) => ExecuteOnSyncContext(() => base.SetItem(index, item));
     protected override void MoveItem(int oldIndex, int newIndex) => ExecuteOnSyncContext(() => base.MoveItem(oldIndex, newIndex));
     protected override void ClearItems() => ExecuteOnSyncContext(() => base.ClearItems());
   public class RootObject
     public Meta meta { get; set; }
     public List<ContentModel> products { get; set; }
   public class Meta
     public int count { get; set; }
     public int limit { get; set; }
     public int page { get; set; }
     public string next_url { get; set; }
   public class ContentModel
     public string Name { get; set; }
     public string ProductUrl { get; set; }
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thanks, let me digest.

If I understand from 30K feet, I will be using the HTTP client that is a part of the default Microsoft.NETCore.App framework. There is/are no other package(s) that I need from NuGet.

0 Votes 0 ·

Hi, from Nuget you need only Newtonsoft.Json if you get JSon and you want deserialize stream to objects.

1 Vote 1 ·