当我把web app的框架从4.0升级到4.6后,我发现HTTP协议库中不再有ReadAsAsync()
方法,取而代之的是GetAsync()
。我需要使用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()
方法实现相同的目标?
发布于 2016-08-04 14:23:21
您可以这样使用它:(您可能希望在另一个线程上运行它,以避免等待响应)
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));
}
}
}
https://stackoverflow.com/questions/38769812
复制