Info and code:
I am designing a UI where the user can design an object to meet their needs. Afterwards, I want them to be able to click a button to download a file containing the JSON representation of this object. A jquery click listener will use ajax to hit the endpoint on the controller when the button is clicked. Currently, the endpoint looks like this:
// 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);
}
As you can see, the mission object's Id is provided to controller, and the mission is grabbed from it. My problem is that I do not know how to convert the object into JSON in a way that I can then write said JSON into a file, and prompt the user to download it.
Things I have tried:
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
- I have looked through questions such as this one
Problems:
- Like I said earlier, I don't know how to go from object to Json to a file
- 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.