我正在尝试使用ASP.NET Web API返回一个JSON文件(用于测试)。
public string[] Get()
{
string[] text = System.IO.File.ReadAllLines(@"c:\data.json");
return text;
}
在Fiddler中,这确实显示为Json类型,但当我在Chrome中调试并查看对象时,它显示为单个行的and数组(左)。正确的图像是我使用对象时应该是什么样子。
谁能告诉我应该返回什么才能以正确的格式获得结果?
发布于 2013-03-31 11:56:36
文件中是否已经包含有效的JSON?如果是这样的话,您应该调用File.ReadAllText
并将其作为单个字符串获取,而不是调用File.ReadAllLines
。然后,您需要将其解析为JSON,以便Web API可以重新序列化它。
public object Get()
{
string allText = System.IO.File.ReadAllText(@"c:\data.json");
object jsonObject = JsonConvert.DeserializeObject(allText);
return jsonObject;
}
这将:
发布于 2013-03-31 12:02:27
我找到了另一个解决方案,如果有人对此感兴趣的话,它也是有效的。
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;
}
发布于 2017-02-09 23:02:12
我需要类似的东西,但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);
}
https://stackoverflow.com/questions/15725884
复制相似问题