0

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.

2 Answers2

3

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.

Mario Vernari
  • 6,649
  • 1
  • 32
  • 44
  • That doesn't send the actual file, but instead gives me the content of the file in the reply. It sort of works, but we want the actual file to be sent –  Feb 07 '18 at 10:30
  • The update didn't work either. Thanks for all the help so far! –  Feb 07 '18 at 10:45
  • 2
    The last hint I wish to give you is about the file, because I had some trouble with a bad encoded text file. Have a check at the encoding of the file, and try to patch it in case (you may use Notepad++, for instance). I suggest to encode as UTF-8 with BOM. – Mario Vernari Feb 07 '18 at 11:34
  • The file is pretty simple, it has nothing but a simple object with a property. 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. I have to figure the correct one out –  Feb 07 '18 at 11:36
1

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.

cortisol
  • 335
  • 2
  • 18