如何生成包含 JSON 结构的要下载的文件?

How to produce a file to download containing a JSON structure?

我的控制器中有这个方法。

public IActionResult Download()
{
  return Json(_context.Users);
}

我注意到它生成了正确的 JSON 结构 但是 它在浏览器中呈现为普通文本。我想把它下载到客户的电脑上。我该怎么做?

我不确定是否应该让我的对象以某种方式流式传输 or maybe create a file on my hard drive and serve it like this

我找不到任何让我印象深刻的东西,就像我们在 C# 中习惯的那样直接和简单。所以我担心我在这里遗漏了一个概念。

将数据转换为字节,然后将这些字节转换为 FileResult。您 return FileResult 和浏览器将在出现 'file' 时正常执行任何操作,通常提示用户或下载。

示例如下:

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

在您的情况下,您只需将 JSON 数据作为字符串。

您可以只将 json 对象写入流或数组并使用 File 方法重载之一。添加方便的Serialize方法

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

    return Encoding.UTF8.GetBytes(result);
}

并按如下方式使用

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

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

如果您使用 .AddJsonOptions()Startup 中设置了特殊的 json 序列化程序设置,您希望使用它们,因为 ASP.NET 框架在 Json 方法中使用它们.在控制器

中注入MvcJsonOptions
IOptions<MvcJsonOptions> _options;

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

并将设置传递给方法

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

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