Search code examples
c#filedownloadasp.net-core-2.2

How to produce a file to download containing a JSON structure?


I have this method in my controller.

public IActionResult Download()
{
  return Json(_context.Users);
}

I noticed that it produces the correct JSON structure but it's being rendered in the browser as common text. I want it to be downloaded to the client's computer. How do I do that?

I'm not sure if is should make my object to stream somehow like this or maybe create a file on my hard drive and serve it like this.

I can't find anything that strikes me as straight-forward and simple like we're used to in C#. So I fear that I'm missing a concept here.


Solution

  • Convert the data into bytes then those bytes into a FileResult. You return the FileResult and the browser will do whatever it does normally when presented with a 'file', usually either prompt the user or download.

    Example below:

    public ActionResult TESTSAVE()
        {
            var data = "YourDataHere";
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(data);
            var output = new FileContentResult(bytes, "application/octet-stream");
            output.FileDownloadName = "download.txt";
    
            return output;
        }
    

    In your case you would simply take your JSON data as a string.