DonkeyBanana
DonkeyBanana

Reputation: 3556

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.

Upvotes: 2

Views: 9878

Answers (2)

Slipoch
Slipoch

Reputation: 785

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.

Upvotes: 3

Alexander
Alexander

Reputation: 9642

You can just write json object to a stream or array and use one of File method overloads. Add convenient Serialize method

private byte[] Serialize(object value, JsonSerializerSettings jsonSerializerSettings)
{
    var result = JsonConvert.SerializeObject(value, jsonSerializerSettings);

    return Encoding.UTF8.GetBytes(result);
}

And use it as following

public IActionResult Download()
{
    var download = Serialize(_context.Users, new JsonSerializerSettings());

    return File(download , "application/json", "file.json");
}

If you set special json serializer settings in Startup using .AddJsonOptions() you would like to use them as ASP.NET framework uses them in Json method. Inject MvcJsonOptions in controller

IOptions<MvcJsonOptions> _options;

public YourController(IOptions<MvcJsonOptions> options)
{
    _options = options;
}

And pass settings to method

public IActionResult Download()
{
    var download = Serialize(_context.Users, _options.Value.SerializerSettings);

    return File(download , "application/json", "file.json");
}

Upvotes: 7

Related Questions