提问者:小点点

返回带有ASP.NET Web API的JSON文件


我正在尝试使用ASP.NET Web API返回一个JSON文件(用于测试)。

public string[] Get()
{
    string[] text = System.IO.File.ReadAllLines(@"c:\data.json");

    return text;
}

在Fiddler中,它确实显示为Json类型,但当我在Chrome中调试并查看对象时,它显示为单独行数组(左)。正确的图像是当我在使用它时该对象应该看起来的样子。

有人能告诉我应该返回什么来实现正确格式的Json结果吗?


共3个答案

匿名用户

文件中是否已经有有效的JSON?如果是这样,您应该调用,而不是调用,并将其作为单个字符串获取。然后您需要将其解析为JSON,以便Web API可以重新序列化它。

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

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

这将:

    <将其作为JSON对象解析为CLR对象/LI>

匿名用户

我找到了另一个解决方案,如果有人感兴趣的话,也是有效的。

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