在我的MVC控制器中,我有以下内容:
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 :(得分:0)
检查以下解决方案以返回响应中的字符串内容
return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(// Your Object
System.Text.Encoding.UTF8, "application/json") };