将Web应用程序的框架从4.0升级到4.6之后,我发现HTTP协议库中不再有ReadAsAsync()方法,而不是ReadAsAsync()。我需要使用GetAsync()序列化我的自定义对象。

使用ReadAsAsync()的代码:

CustomResponse customResponse = client.ReadAsAsync("api/xxx", new StringContent(new JavaScriptSerializer().Serialize(request), Encoding.UTF8, "application/json")).Result;


另一个基于ReadAsAsync()的示例

CustomResponse customResponse = await Response.Content.ReadAsAsync<CustomResponse>();


如何使用GetAsync()方法实现相同的目标?

最佳答案

您可以通过以下方式使用它:
(您可能希望在另一个线程上运行它以避免等待响应)

using (HttpClient client = new HttpClient())
{
    using (HttpResponseMessage response = await client.GetAsync(page))
    {
        using (HttpContent content = response.Content)
        {
            string contentString = await content.ReadAsStringAsync();
var myParsedObject = (MyObject)(new JavaScriptSerializer()).Deserialize(contentString ,typeof(MyObject));
        }

    }
}

10-07 14:22