【问题标题】:Convert an object to JSON, then download that JSON as a text file [Asp.net core]将对象转换为 JSON,然后将该 JSON 下载为文本文件 [Asp.net 核心]
【发布时间】:2021-08-22 00:04:26
【问题描述】:

信息和代码:

我正在设计一个用户界面,用户可以在其中设计一个对象来满足他们的需求。之后,我希望他们能够单击按钮下载包含此对象的 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 被提供给控制器,并从中获取任务。我的问题是我不知道如何将对象转换为 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
  1. 我查看了诸如this one之类的问题

问题:

  1. 就像我之前说的,我不知道如何从对象到 Json 再到文件
  2. 基本上我可以在网上找到的所有教程都非常过时,或者需要文件路径,假设您提供的是预先存在的文件,但我没有。

【问题讨论】:

  • 你试过简单的return Ok(toDownload);这将返回没有序列化的json对象
  • @Jawad 我需要让用户下载一个包含所述 JSON 的文件,而不仅仅是返回 json

标签: c# json file asp.net-core download


【解决方案1】:
  1. 就像我之前说的,我不知道如何从对象到 Json 到文件

    1. 您可以使用 System.Text.Json 命名空间来序列化和反序列化 JavaScript 对象表示法 (JSON)。
    2. string jsonString = JsonSerializer.Serialize(weatherForecast);
  2. 基本上我可以在网上找到的所有教程都非常过时,或者需要文件路径,假设您提供的是预先存在的文件,但我没有。

    1. 您可以返回FileContentResult

    2. 您可以查看下面的示例。

    3. 代码

       [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
           };
       }
      
    4. 结果

【讨论】:

    【解决方案2】:

    这可能对你有用:

    [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 的正确返回类型。

    我没有尝试它如何处理较大的对象,也许需要一些优化。


    或者,您还可以以更“花哨”的方式设置标题,这将正确地转义您的文件名并为您提供一些额外的属性来设置。

    HttpContext.Response.Headers.Add("Content-Disposition", new System.Net.Mime.ContentDisposition
    {
        FileName = "export.json",
        Inline   = false
    }.ToString());
    

    【讨论】:

      猜你喜欢
      • 2017-10-25
      • 2014-03-19
      • 1970-01-01
      • 2020-10-06
      • 2020-02-21
      • 1970-01-01
      • 1970-01-01
      • 2011-10-20
      • 2020-02-24
      相关资源
      最近更新 更多