【问题标题】:Create Json-File from Website-Content and download it从网站内容创建 Json 文件并下载它
【发布时间】:2020-09-13 09:19:36
【问题描述】:

当我使用网站上的导出按钮时,我必须为我的网站实现一个功能,该功能从预订列表中创建一个 Json 文件并下载它。 而且我不知道它是如何工作的^^ The Website Looks like this:

到目前为止,我只有以下代码:

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

预订保存在名为 bookings 的 IList 中。并且列表保存在缓存中。

感谢帮助:)

【问题讨论】:

  • @Macro 你遇到了什么问题?
  • 当我按下导出按钮时,我不知道如何将列表导出到 Json 文件并开始下载该文件 ^^

标签: c# json asp.net-mvc asp.net-core


【解决方案1】:

你可以通过 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;
}

This post

【讨论】:

  • 但我必须从网站下载 json 文件(并先创建它)到我的电脑。 ^^ 而且我不知道如何开始下载。首先,我应该得到一个资源管理器窗口,我可以在其中选择要下载文件的路径。或者,如果可能,从 Edge 页面底部的标准下载栏。 ^^
  • 是的,它的工作原理,非常感谢你 :D 你也许知道我怎样才能得到一个很好的格式?都在一排^^
  • 你可以试试 JsonConvert.SerializeObject(jsonString, Formatting.Indented); ?
【解决方案2】:

如果您将文件保存在服务器文件夹中,则可以将其用作可下载文件。

例子:

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"}

     };
}

【讨论】:

  • 哇,现在这有点太复杂了 :D 到目前为止我们还没有服务器。只是电脑上正在运行的程序。但是感谢您的帮助:)
猜你喜欢
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-06
相关资源
最近更新 更多