我正在尝试使用ASP.NET Web API返回一个JSON文件(用于测试)。
public string[] Get()
{
string[] text = System.IO.File.ReadAllLines(@"c:\data.json");
return text;
}
在Fiddler中,它确实显示为Json类型,但当我在Chrome中调试并查看对象时,它显示为单独行数组(左)。正确的图像是当我在使用它时该对象应该看起来的样子。
有人能告诉我应该返回什么来实现正确格式的Json结果吗?
文件中是否已经有有效的JSON?如果是这样,您应该调用
public object Get()
{
string allText = System.IO.File.ReadAllText(@"c:\data.json");
object jsonObject = JsonConvert.DeserializeObject(allText);
return jsonObject;
}
这将:
我找到了另一个解决方案,如果有人感兴趣的话,也是有效的。
public HttpResponseMessage Get()
{
var stream = new FileStream(@"c:\data.json", FileMode.Open);
var result = Request.CreateResponse(HttpStatusCode.OK);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return result;
}
我需要类似的内容,但IHttpActionResult(WebApi2)是必需的。
public virtual IHttpActionResult Get()
{
var result = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.OK)
{
Content = new System.Net.Http.ByteArrayContent(System.IO.File.ReadAllBytes(@"c:\temp\some.json"))
};
result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
return ResponseMessage(result);
}