我在我的控制器此方法。
public IActionResult Download()
{
return Json(_context.Users);
}
我注意到,它产生正确的JSON结构,但它在浏览器中常见的文字渲染。我希望它被下载到客户端的计算机。我怎么做?
我不知道是否就是应该让我的对象到流莫名其妙like this或者也许我的硬盘上创建一个文件,并为它服务like this。
我无法找到任何东西,在我看来是直接的,简单的就像我们在C#中使用。所以我担心,我在这里失踪的概念。
转换数据为字节,然后这些字节到FileResult。您返回FileResult,浏览器将做的时候以“文件”提出任何它一般不会,通常要么提示用户或下载。
实施例下面:
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");
}
如果您在使用Startup
在.AddJsonOptions()
设置特殊的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");
}