尝试从Web API调用中读取响应

时间:2014-12-07 00:16:02

标签: asp.net-mvc asp.net-web-api2

我正在尝试从Web API调用中读取我的员工列表,但却收到错误。

using (var client = new HttpClient())
{
   client.BaseAddress = new Uri("http://myApiUrl");
   client.DefaultRequestHeaders.Accept.Clear();
   client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

   HttpResponseMessage response = await client.GetAsync("api/hr/employees");
   if (response.IsSuccessStatusCode)
   {
      List<Employee> employees = response.Content.ReadAsAsync(IEnumerable<Employee>).Result;
   }
}

我目前得到的错误是: System.Net.Http.HttpContent不包含ReadAsAsync的定义...

我做错了什么?

2 个答案:

答案 0 :(得分:2)

ReadAsAsync不是HttpClient类的方法。如果要读取数据并将其强制转换为对象,可以使用:

HttpResponseMessage response = await client.GetAsync("api/hr/employees");
if (response.IsSuccessStatusCode)
{
    var result= await response.Content.ReadAsStringAsync();
    List<Employee> employees = JsonConvert.DeserializeObject<Employee>(result);
}

答案 1 :(得分:0)

尝试

List<Employee> employees = response.Content.ReadAsAsync<IEnumerable<Employee>>().Result;