将对象转换为 JSON,然后将 JSON 下载为文本文件 [Asp.net core]
Convert an object to JSON, then download that JSON as a text file [Asp.net core]
信息和代码:
我正在设计一个 UI,用户可以在其中设计一个对象来满足他们的需要。之后,我希望他们能够单击一个按钮来下载包含此对象的 JSON 表示的文件。单击按钮时,jquery 单击侦听器将使用 ajax 命中控制器上的端点。目前,端点如下所示:
// GET: api/Missions/DownloadMission?id
[HttpGet]
[Route("api/Missions/DownloadMission{id}")]
public IHttpActionResult DownloadMission(int id)
{
Mission toDownload = db.Missions.Find(id);
string json = JsonConvert.SerializeObject(toDownload);
}
如你所见,任务对象的Id提供给controller,并从中抓取任务。我的问题是我不知道如何将对象转换为 JSON,然后我可以将 JSON 写入文件,并提示用户下载它。
我尝试过的事情:
using (MemoryStream stream = new MemoryStream())
{
using (StreamWriter writer = new StreamWriter(stream))
{
while(missionJson.nex)
}
return File(stream, "text/plain");
}
//I tried playing around with this type of set up, but could still not get the intended results
byte[] bytes = System.IO.File.ReadAllBytes(data);
var output = new FileContentResult(bytes, "application/octet-stream");
output.FileDownloadName = "download.txt";
return output;
Mission toDownload = db.Missions.Find(id);
string fileName = @"~\Mission.txt";
try
{
if (File.Exists(fileName))
{
File.Delete(fileName);
}
using (FileStream fs = File.Create(fileName))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Converters.Add(new JavaScriptDateTimeConverter());
serializer.NullValueHandling = NullValueHandling.Ignore;
using (StreamWriter sw = new StreamWriter(fileName))
using (JsonWriter writer = new JsonTextWriter(sw))
{
serializer.Serialize(writer, toDownload);
}
return File(fs, "Mission.txt");
}
}
catch (Exception Ex)
{
Console.WriteLine(Ex.ToString());
}
// In this case, "File()" isnt recognized, but this is probably the closest i've been
- 我已经看过this one
等问题
问题:
- 就像我之前说的,我不知道如何从对象到 Json 再到文件
- 基本上我能在网上找到的所有教程都非常过时,或者需要文件路径,假设您提供的是预先存在的文件,而我不是。
-
Like I said earlier, I don't know how to go from object to Json to a file
- 您可以使用 System.Text.Json 命名空间来序列化和反序列化 JavaScript Object Notation (JSON)。
string jsonString = JsonSerializer.Serialize(weatherForecast);
-
basically all tutorials I can find online are very outdated, or require a filepath, presuming you are providing a pre-existing file, which I am not.
您可以return FileContentResult.
您可以查看下面的示例。
代码
[HttpGet("DownloadMission/{id}")]
public FileContentResult DownloadMission(int id)
{
Mission toDownload = new Mission { Id = 1, name = "test" };
string jsonString = JsonSerializer.Serialize(toDownload);
var fileName = "test.txt";
var mimeType = "text/plain";
var fileBytes = Encoding.ASCII.GetBytes(jsonString);
return new FileContentResult(fileBytes, mimeType)
{
FileDownloadName = fileName
};
}
结果
这对你有用:
[HttpGet]
[Route("api/Missions/DownloadMission{id}")]
public IHttpActionResult DownloadMission(int id)
{
var toDownload = db.Missions.Find(id);
// if you set this, the browser asks the user to save 'export.json'
HttpContext.Response.Headers.Add("Content-Disposition", "attachment; filename=export.json");
// return content as json with your default json serializer settings
return new JsonResult(toDownload);
}
如前所述,将 IHttpActionResult
替换为 IActionResult
,这是 ASP.NET Core 的正确 return 类型。
我没有尝试它在更大 objects 下的表现,也许需要一些优化。
或者,您也可以以更“花哨”的方式设置 header,这将正确地转义您的文件名并为您提供一些额外的属性来设置。
HttpContext.Response.Headers.Add("Content-Disposition", new System.Net.Mime.ContentDisposition
{
FileName = "export.json",
Inline = false
}.ToString());
信息和代码:
我正在设计一个 UI,用户可以在其中设计一个对象来满足他们的需要。之后,我希望他们能够单击一个按钮来下载包含此对象的 JSON 表示的文件。单击按钮时,jquery 单击侦听器将使用 ajax 命中控制器上的端点。目前,端点如下所示:
// GET: api/Missions/DownloadMission?id
[HttpGet]
[Route("api/Missions/DownloadMission{id}")]
public IHttpActionResult DownloadMission(int id)
{
Mission toDownload = db.Missions.Find(id);
string json = JsonConvert.SerializeObject(toDownload);
}
如你所见,任务对象的Id提供给controller,并从中抓取任务。我的问题是我不知道如何将对象转换为 JSON,然后我可以将 JSON 写入文件,并提示用户下载它。
我尝试过的事情:
using (MemoryStream stream = new MemoryStream())
{
using (StreamWriter writer = new StreamWriter(stream))
{
while(missionJson.nex)
}
return File(stream, "text/plain");
}
//I tried playing around with this type of set up, but could still not get the intended results
byte[] bytes = System.IO.File.ReadAllBytes(data);
var output = new FileContentResult(bytes, "application/octet-stream");
output.FileDownloadName = "download.txt";
return output;
Mission toDownload = db.Missions.Find(id);
string fileName = @"~\Mission.txt";
try
{
if (File.Exists(fileName))
{
File.Delete(fileName);
}
using (FileStream fs = File.Create(fileName))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Converters.Add(new JavaScriptDateTimeConverter());
serializer.NullValueHandling = NullValueHandling.Ignore;
using (StreamWriter sw = new StreamWriter(fileName))
using (JsonWriter writer = new JsonTextWriter(sw))
{
serializer.Serialize(writer, toDownload);
}
return File(fs, "Mission.txt");
}
}
catch (Exception Ex)
{
Console.WriteLine(Ex.ToString());
}
// In this case, "File()" isnt recognized, but this is probably the closest i've been
- 我已经看过this one 等问题
问题:
- 就像我之前说的,我不知道如何从对象到 Json 再到文件
- 基本上我能在网上找到的所有教程都非常过时,或者需要文件路径,假设您提供的是预先存在的文件,而我不是。
-
Like I said earlier, I don't know how to go from object to Json to a file
- 您可以使用 System.Text.Json 命名空间来序列化和反序列化 JavaScript Object Notation (JSON)。
string jsonString = JsonSerializer.Serialize(weatherForecast);
-
basically all tutorials I can find online are very outdated, or require a filepath, presuming you are providing a pre-existing file, which I am not.
您可以return FileContentResult.
您可以查看下面的示例。
代码
[HttpGet("DownloadMission/{id}")] public FileContentResult DownloadMission(int id) { Mission toDownload = new Mission { Id = 1, name = "test" }; string jsonString = JsonSerializer.Serialize(toDownload); var fileName = "test.txt"; var mimeType = "text/plain"; var fileBytes = Encoding.ASCII.GetBytes(jsonString); return new FileContentResult(fileBytes, mimeType) { FileDownloadName = fileName }; }
结果
这对你有用:
[HttpGet]
[Route("api/Missions/DownloadMission{id}")]
public IHttpActionResult DownloadMission(int id)
{
var toDownload = db.Missions.Find(id);
// if you set this, the browser asks the user to save 'export.json'
HttpContext.Response.Headers.Add("Content-Disposition", "attachment; filename=export.json");
// return content as json with your default json serializer settings
return new JsonResult(toDownload);
}
如前所述,将 IHttpActionResult
替换为 IActionResult
,这是 ASP.NET Core 的正确 return 类型。
我没有尝试它在更大 objects 下的表现,也许需要一些优化。
或者,您也可以以更“花哨”的方式设置 header,这将正确地转义您的文件名并为您提供一些额外的属性来设置。
HttpContext.Response.Headers.Add("Content-Disposition", new System.Net.Mime.ContentDisposition
{
FileName = "export.json",
Inline = false
}.ToString());