2014-06-05 181 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") };

返回字符串的内容