[英]Return JSON file with ASP.NET Web API
该文件中是否已包含有效的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;
}
这将:
我找到了另一个解决方案,如果有人有兴趣也可以。
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.