Return JSON file with ASP.NET Web API
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;
}
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)