Return Json 文件来自 APi 端点

Return Json File From APi Endpoint

我需要 return Json 我从数据库中以字符串形式获取的文件。 当有人访问此 link.

时,我需要开始下载 Json 文件

这是我现在拥有的代码。

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;
}

您可以 return 并使用此 API 方法从 URL 下载 Json 文件:

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");
}