我习惯在Net Core工作。当我调用 RestApi 时,我会像这样读取检索到的数据。
HttpResponseMessage response = client.PostAsJsonAsync(url, param).Result;
value = response.Content.ReadAsJsonAsync<R>().Result;
现在,我回到了 Framework 4.5 中,我需要替换
ReadAsJsonAsync
替换它的最佳方法是什么?
谢谢
最佳答案
您可以只安装 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>();
关于框架 4.5 中的 c# ReadAsJsonAsync,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53764090/