I have a txt file which has some data in it. I would like to return the data in JSON format.
Why is it that when i do this in my controller, i am able to display the result (but not in JSON format):
public IHttpActionResult Get()
{
return new FileReaderClient("C:\\Users\\attsuap1\\Desktop\\1milliontest.txt");
}
However when i do this i get the result as: {"Data":{}}
public IHttpActionResult Get()
{
var result = new FileReaderClient("C:\\Users\\attsuap1\\Desktop\\1milliontest.txt");
return Ok(new { Data = result });
}
If i just return result:
public IHttpActionResult Get()
{
var result = (new FileReaderClient("C:\\Users\\attsuap1\\Desktop\\1milliontest.txt"));
return result;
}
I do get the data however it is not in the Json format that i want e.g. {"Data": "Allthecontentinhere"}. I tried return Json(result) that did not work too.
Here is my FileReaderClient.cs class
public class FileReaderClient : IHttpActionResult
{
private readonly string filePath;
private readonly string contentType;
public FileReaderClient(string filePath, string contentType = null)
{
this.filePath = filePath;
this.contentType = contentType;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
return Task.Run(() =>
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StreamContent(File.OpenRead(filePath))
};
var contentType = this.contentType ?? MimeMapping.GetMimeMapping(Path.GetExtension(filePath));
response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
return response;
}, cancellationToken);
}
}
How can i edit my code such that the data in the file is returned in JSON format?
Json()method) returning reasonable object should automatically produce JSON response. In current state of the post there is no way to know what you want to achieve and why your customFileReaderClientdoes not represent data you want. Consider reading minimal reproducible example guidance on posting code and edit post to clarify.Physical Path given but virtual path expected. Then i read that Server.Mappath is not needed when i know the path in one of the stackoverflow answersreturn result, I get a valid JSON. What do you get? You said: "I do get the data however it is not in Json format".