0

I must implement a function for my Website, that creates a Json file from a list of bookings and download it, when i use the export-button on the site. And i have NO idea how that works ^^ The Website Looks like this:

Until now I have only the following Code:

[HttpGet]
    public IActionResult Export()
    {
        var bookings = _cache.GetOrCreate(BookingsCacheKey, BookingListFactory);
        string output = JsonConvert.SerializeObject(bookings);
        return View("Index");
    }

The bookings are saved in a IList called bookings. And the list is saved in the cache.

Thx for help :)

Marco
  • 33
  • 7

2 Answers2

1

u can just return the object via a Ok response

[HttpGet]
public IActionResult Export()
{
    var bookings = _cache.GetOrCreate(BookingsCacheKey, BookingListFactory);
    string output = JsonConvert.SerializeObject(bookings);

    byte[] bytes = System.Text.Encoding.UTF8.GetBytes(output);
    var output = new FileContentResult(bytes, "application/octet-stream");
    output.FileDownloadName = "download.txt";

    return output;
}

look at This post

  • But i must download the json file (and create it first) from the Website to my PC. ^^ And i don't know how to start a download. At first i should get a Explorer window, where i can choose, in what path i want to download the file. Or, if possible, the Standard donwload bar in the Bottom of the page from Edge. ^^ – Marco May 26 '20 at 14:47
  • Yay, it works, thank you very much :D Do you Maybe know how i can get it in a nice Format? It is all in one row ^^ – Marco May 26 '20 at 14:58
  • can u try JsonConvert.SerializeObject(jsonString, Formatting.Indented); ? – Lukas Coomans May 26 '20 at 15:04
0

if you save the file in a server folder, then you can use it as a downloadable file.

Example:

var test = new
{
    Id = 0,
    contains = "Test"
};//Save the file
string json = JsonConvert.SerializeObject(test);
System.IO.File.WriteAllText(@"wwwroot\\json\\test.json", json);


string fileName = "test.json";//Find the file in the path
var path = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\\json\\", fileName);
var memory = new MemoryStream();
using (var stream = new FileStream(path, FileMode.Open))
{
    await stream.CopyToAsync(memory);
}
memory.Position = 0;//Return file with donwload
return File(memory, GetContentType(path), Path.GetFileName(path));

GetContentType and GetMimeTypes auxiliary methods:

private string GetContentType(string path)
{
    var types = GetMimeTypes();
    var ext = Path.GetExtension(path).ToLowerInvariant();
    return types[ext];
}

private Dictionary<string, string> GetMimeTypes()
{
    return new Dictionary<string, string>
    {
        {".json", "application/json"}

     };
}
  • Wow, that's a bit too complex for now :D We don''t have a Server so far. Just the running program on the pc. But thanks for your help :) – Marco May 26 '20 at 16:31