Reputation:
I'm building a simple API using .NET core, and would like to send a simple .json file to the client once he reaches a certain endpoint on the API.
So far I'm having very little success, but what I currently have is the following:
public IActionResult yaddayadda(){
var filePath = "./Data/file.json";
using (var stream = new FileStream(@filePath, FileMode.Open))
{
return new FileStreamResult(stream, "application/json");
}
}
This gets me nothing. (The path for the file is correct)
Thanks!
EDIT: I've experimented with different content-types, and even though it's not the correct one, multipart/form-data allows me to download a file, but it has no extension.
Upvotes: 0
Views: 942
Reputation: 363
Try to use
byte[] fileBytes = System.IO.File.ReadAllBytes(filePath);
string fileName = "file.json";
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
Useful link.
Upvotes: 1
Reputation: 7306
Try this, by avoiding the disposal (so the closure) of the stream:
public IActionResult yaddayadda(){
var filePath = "./Data/file.json";
var stream = new FileStream(@filePath, FileMode.Open);
return new FileStreamResult(stream, "application/json");
}
UPDATE: Here is another way I use with pictures, although should behave the same:
public IActionResult yaddayadda()
{
var filePath = "./Data/file.json";
return this.PhysicalFile(filePath, "application/json");
}
Note that this solution implies that you're deriving from the Controller class, because the "PhysicalFile" method is exposed by.
Upvotes: 3