2013-08-28 100 views
1

我有一个ASP.NET MVC 4应用程序,其中有一个控制器接收XHR请求并返回JSON的操作。在此操作中,我想调用一个WEB API,将响应作为JSON接收,并使用JSON字符串作为操作返回值。如何从Web API响应中获取JSON字符串

(我不允许直接用JavaScript调用web API,我需要通过服务器去)

我设法使请求发送到Web API,但我无法弄清楚如何读出JSON字符串。

这里是我的方法:

public ActionResult Index() 
    { 
     String ret = ""; 
      HttpClient client = new HttpClient(); 
      client.BaseAddress = new Uri("http://localhost:8080/"); 

      client.DefaultRequestHeaders.Accept.Add(
       new MediaTypeWithQualityHeaderValue("application/json")); 

      HttpResponseMessage response = client.GetAsync("api/stuff").Result; 
      if (response.IsSuccessStatusCode) 
      { 
       // How do I get the JSON string out of the response object? 
       //ret = response.?? 
      } 
      else 
      {      
      } 

      return Content(ret, "application/json"); 
    } 

回答

4

这个怎么样。

string json = await response.Content.ReadAsStringAsync(); 
+0

谢谢!在向方法添加async关键字并使其返回Task 之后,它可以工作。 – Thea