1

I am used to work in Net Core. When I call a RestApi I read retrieved data like this.

  HttpResponseMessage response = client.PostAsJsonAsync(url, param).Result;
    value = response.Content.ReadAsJsonAsync<R>().Result;

Now, I am back in Framework 4.5 and i need a replace to

ReadAsJsonAsync

What is the best way to replace it?

Thanks

Diego
  • 2,238
  • 4
  • 31
  • 68
  • 3
    Why do use the Async methods but did not want them behave async? That is like playing with water but did not like to become wet ... – Sir Rufo Dec 13 '18 at 14:32
  • Use https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Client/ – Sir Rufo Dec 13 '18 at 14:39
  • 1
    Do not use Task.Result, instead do [GetAwaiter().GetResult();](https://stackoverflow.com/a/38530225/6640527) – Diego Osornio Dec 13 '18 at 15:08
  • @Unnamed or indeed, better yet, `await` it if possible. – Jon Hanna Dec 13 '18 at 15:20
  • @Jon Yes, the only case to not await async code will be when for some reason you need to run it synchronously, just in that case we will prefer GetAwaiter.GetResult() over Task.Result. – Diego Osornio Dec 13 '18 at 15:22

1 Answers1

3

You could just install the Newtonsoft.Json NuGet package and implement the ReadAsJsonAsync extension method yourself. It's pretty simple:

public static class HttpClientExtensions
{
    public static async Task<T> ReadAsJsonAsync<T>(this HttpContent content)
    {
        var dataAsString = await content.ReadAsStringAsync();
        return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(dataAsString);
    }
}

By the way, you should await async methods and not block on the Result property:

value = await response.Content.ReadAsJsonAsync<R>();
mm8
  • 163,881
  • 10
  • 57
  • 88
  • if possible use [ConfigureAwait(false)](https://stackoverflow.com/a/13494570/6640527) – Diego Osornio Dec 13 '18 at 15:27
  • 2
    That is already included in https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Client/ => ReadAsAsync which is available for .net Framework 4.5 and up – Sir Rufo Dec 13 '18 at 17:56
  • @SirRufo Which namespace? I am here specifically because I cannot find this method in Microsoft.AspNet.WebApi.Client, using Framework 4.6.1. – Daniel Apr 29 '21 at 20:11
  • @Daniel https://fuget.org is a great source for looking into nuget packages. Here we go: https://www.fuget.org/packages/Microsoft.AspNet.WebApi.Client/5.2.7/netstandard2.0/lib/System.Net.Http.Formatting.dll/System.Net.Http/HttpContentExtensions#ReadAsAsync – Sir Rufo Apr 29 '21 at 20:41
  • @SirRufo Ah, I should have deleted this comment. I had forgotten I actually pulled the trigger on it. I found the method, and the fault was all mine. I was looking specifically for ReadAsJsonAsync--as named in this question and answer--but did not notice the correct name (ReadAsAsync) in your comment. Once I did, it was easy to find in System.Net.Http.Formatting. Thank you, though. – Daniel Apr 30 '21 at 14:06