Home > Enterprise >  Return Json File From APi Endpoint
Return Json File From APi Endpoint

Time:05-31

I need to return Json file that I get as a string from database. I need to start a download for Json file when someone goes to this link.

This is the code I have right now.

public ActionResult<HttpResponseMessage> Index(string guid)
{
    var filestring = DbContext.Tasks.SingleOrDefault(t => t.GUID == guid).FinishedFiles;
    if (filestring == null)
        return StatusCode(410);

    var response = new HttpResponseMessage();

    response.StatusCode = HttpStatusCode.OK;
    response.Content = new StreamContent(filestring);
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
    response.Content.Headers.ContentDisposition.FileName = "result.json";
    return response;
}

CodePudding user response:

You can return and download Json file from URL with this API method:

public IActionResult Index(string guid)
{
    var filestring = DbContext.Tasks.SingleOrDefault(t => t.GUID == guid).FinishedFiles;
    if (filestring == null)
        return StatusCode(410);

    var bytes = Encoding.UTF8.GetBytes(filestring);
    MemoryStream ms = new MemoryStream(bytes);
    return File(fileStream: ms, contentType: "application/json", fileDownloadName: "result.json");
}
  • Related