我必须为我的网站实现一个功能,当我使用网站上的导出按钮时,该功能可以从预订列表中创建一个Json文件并下载。 而且我不知道那是如何工作的^^ The Website Looks like this:
直到现在我只有以下代码:
[HttpGet]
public IActionResult Export()
{
var bookings = _cache.GetOrCreate(BookingsCacheKey, BookingListFactory);
string output = JsonConvert.SerializeObject(bookings);
return View("Index");
}
将预订保存在称为预订的IList中。并将列表保存在缓存中。
寻求帮助:)
答案 0 :(得分:1)
u可以通过Ok响应返回对象
[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;
}
答案 1 :(得分:0)
如果将文件保存在服务器文件夹中,则可以将其用作可下载文件。
示例:
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和GetMimeTypes辅助方法:
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"}
};
}