ojh*_*ins 26 javascript c# json asp.net-web-api
我试图使用ASP.NET Web API返回一个JSON文件(用于测试).
public string[] Get()
{
string[] text = System.IO.File.ReadAllLines(@"c:\data.json");
return text;
}
Run Code Online (Sandbox Code Playgroud)
在Fiddler中,它确实显示为Json类型,但是当我在Chrome中调试并查看它出现的对象和各行的数组(左)时.正确的图像是我使用它时对象应该是什么样子.
任何人都可以告诉我应该返回什么以正确的格式获得Json结果?
Eil*_*lon 29
该文件中是否已包含有效的JSON?如果是这样,而不是打电话给File.ReadAllLines
你应该调用File.ReadAllText
并将其作为单个字符串.然后,您需要将其解析为JSON,以便Web API可以重新序列化它.
public object Get()
{
string allText = System.IO.File.ReadAllText(@"c:\data.json");
object jsonObject = JsonConvert.DeserializeObject(allText);
return jsonObject;
}
Run Code Online (Sandbox Code Playgroud)
这将:
ojh*_*ins 22
我找到了另一个解决方案,如果有人有兴趣也可以.
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;
}
Run Code Online (Sandbox Code Playgroud)
我需要类似的东西,但需要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);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
33910 次 |
最近记录: |