代码之家  ›  专栏  ›  技术社区  ›  Diego

框架4.5中的c#ReadAsJsonAsync

  •  1
  • Diego  · 技术社区  · 6 年前

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

    现在,我回到了Framework4.5中,我需要一个替换来

    替换它的最佳方法是什么?

    谢谢

    1 回复  |  直到 6 年前
        1
  •  3
  •   mm8    6 年前

    您只需安装 Newtonsoft.Json NuGet包并实现 ReadAsJsonAsync 自己扩展方法。这很简单:

    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);
        }
    }
    

    顺便说一下,您应该等待异步方法,而不是在 Result 财产:

    value = await response.Content.ReadAsJsonAsync<R>();