Reputation: 33
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 :)
Upvotes: 0
Views: 1380
Reputation: 101
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"}
};
}
Upvotes: 0
Reputation: 63
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
Upvotes: 1