使用ASP.NET Web API返回JSON文件

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结果?

alt http://i47.tinypic.com/fyd4ww.png

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)

这将:

  1. 以字符串形式读取文件
  2. 将其作为JSON对象解析为CLR对象
  3. 将其返回到Web API,以便将其格式化为JSON(或XML,或其他)


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)

  • +1:HttpResponseMessage可能已被弃用,但它适用于JSON属性名称无效CLR的情况(例如,其中包含空格).你的回答给了我一些线索,我需要将生成的原始文本作为JSON返回.谢谢 (4认同)
  • 通用的HttpResponseMessage现已弃用,因为它不是Type <T>安全的.http://stackoverflow.com/questions/10655350/returning-http-status-code-from-asp-net-mvc-4-web- API控制器 (2认同)

Ale*_*sco 5

我需要类似的东西,但需要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)