简体   繁体   English

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

[英]Return JSON file with ASP.NET Web API

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). 在Fiddler中,它确实显示为Json类型,但是当我在Chrome中调试并查看它出现的对象和各行的数组(左)时。 The right image is what the object should look like when I am using it. 正确的图像是我使用它时对象应该是什么样子。

Can anyone tell me what I should return to achieve a Json result in the correct format? 任何人都可以告诉我应该返回什么以正确的格式获得Json结果?

ALT

Does the file already has valid JSON in it? 该文件中是否已包含有效的JSON? If so, instead of calling File.ReadAllLines you should call File.ReadAllText and get it as a single string. 如果是这样,而不是调用File.ReadAllLines你应该调用File.ReadAllText并把它作为一个字符串。 Then you need to parse it as JSON so that Web API can re-serialize it. 然后,您需要将其解析为JSON,以便Web API可以重新序列化它。

public object Get()
{
    string allText = System.IO.File.ReadAllText(@"c:\data.json");

    object jsonObject = JsonConvert.DeserializeObject(allText);
    return jsonObject;
}

This will: 这将:

  1. Read the file as a string 以字符串形式读取文件
  2. Parse it as a JSON object into a CLR object 将其作为JSON对象解析为CLR对象
  3. Return it to Web API so that it can be formatted as JSON (or XML, or whatever) 将其返回到Web API,以便将其格式化为JSON(或XML,或其他)

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;
}

I needed something similar, but IHttpActionResult ( WebApi2 ) was required. 我需要类似的东西,但需要IHttpActionResultWebApi2 )。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM