C# 使用 ASP.NET Web API 返回 JSON 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15725884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Return JSON file with ASP.NET Web API
提问by ojhawkins
I am trying to return a JSON file using ASP.NET Web API (for testing).
我正在尝试使用 ASP.NET Web API(用于测试)返回一个 JSON 文件。
public string[] Get()
{
string[] text = System.IO.File.ReadAllLines(@"c:\data.json");
return text;
}
In Fiddler this does appear as a Json type but when I debug in Chrome and view the object it appears as and array of individual lines (left). The right image is what the object should look like when I am using it.
在 Fiddler 中,这确实显示为 Json 类型,但是当我在 Chrome 中调试并查看对象时,它显示为单行数组(左)。正确的图像是我使用对象时该对象的外观。
Can anyone tell me what I should return to achieve a Json result in the correct format?
谁能告诉我我应该返回什么才能以正确的格式获得 Json 结果?
采纳答案by Eilon
Does the file already has valid JSON in it? If so, instead of calling File.ReadAllLines
you should call File.ReadAllText
and get it as a single string. Then you need to parse it as JSON so that Web API can re-serialize it.
文件中是否已经包含有效的 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;
}
This will:
这会:
- Read the file as a string
- Parse it as a JSON object into a CLR object
- Return it to Web API so that it can be formatted as JSON (or XML, or whatever)
- 将文件作为字符串读取
- 将其作为 JSON 对象解析为 CLR 对象
- 将其返回到 Web API,以便将其格式化为 JSON(或 XML,或其他)
回答by ojhawkins
I found another solution which works also if anyone was interested.
我找到了另一种解决方案,如果有人感兴趣,它也可以使用。
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;
}
回答by Alex Nolasco
I needed something similar, but IHttpActionResult(WebApi2) was required.
我需要类似的东西,但需要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);
}