HttpContent ReadAsAsync with .NET Core 2

Full source code available here.

If you are used to using HttpContent.ReadAsAsync you might be surprised to learn that it is missing from .NET Core 2. You can try adding Microsoft.AspNet.WebApi.Client but you might get warnings or errors.

At some point Microsoft will come out with an updated NuGet package, but in the meantime here is a work around.

At this extension method to your code.

 1using Newtonsoft.Json;
 2using System.Net.Http;
 3using System.Threading.Tasks;
 4
 5namespace ReadAsAsyncCore
 6{
 7    public static class HttpContentExtensions
 8    {
 9        public static async Task<T> ReadAsJsonAsync<T>(this HttpContent content)
10        {
11            string json = await content.ReadAsStringAsync();
12            T value = JsonConvert.DeserializeObject<T>(json);
13            return value;
14        }
15    }
16}

And use like this.

1HttpResponseMessage httpResponse = await httpClient.GetAsync(requestEndpoint);
2List<Product> products = await httpResponse.Content.ReadAsJsonAsync<List<Product>>();

Full source code available here.

comments powered by Disqus

Related