[英]c# ReadAsJsonAsync in framework 4.5
我習慣在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>();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.