Return JSON file with ASP.NET Web API

I am trying to return a JSON file using ASP.NET Web API (for testing).

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.

Can anyone tell me what I should return to achieve a Json result in the correct format?

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


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.

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)

  • 如果有人感兴趣,我发现了另一种解决方案。

    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:tempsome.json"))
        };
    
        result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
        return ResponseMessage(result);
    }
    
    链接地址: http://www.djcxy.com/p/20430.html

    上一篇: Web Api和JSON?

    下一篇: 使用ASP.NET Web API返回JSON文件