2014-06-05 179 views
1

在我的MVC控制器從網絡API控制器返回異步任務,我有以下幾點:通過Ajax請求的JSON

public async Task<ActionResult> Get() 
{ 
    WebClient client = new WebClient(); 
    var result = new ContentResult 
     { 
      Content = await client.DownloadStringTaskAsync(url), 
      ContentType = "application/json" 
     }; 

    return result; 
} 

但現在,我使用的是MVC的Web API,我該如何改變這種迴歸一個字符串,而不是通過Ajax請求的ActionResult?

我試過以下,它的工作原理,但我得到一個字符串,而不是一個JSON對象。

public async Task<HttpResponseMessage> Get() 
{ 
    WebClient client = new WebClient(); 

    String result = await client.DownloadStringTaskAsync(url); 

    var resp = new HttpResponseMessage(HttpStatusCode.OK); 
    resp.Content = new ObjectContent<object>(result, new JsonMediaTypeFormatter()); 
    resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); 

    return resp; 

} 

任何想法?

回答

0

檢查下面的解決方案以響應

return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(// Your Object System.Text.Encoding.UTF8, "application/json") };

返回字符串的內容