ASP.NET MVC 返回文件结果,其中包含要在客户端处理的其他数据

ASP.NET MVC Return File result with additional data to process on client side

本文关键字:客户端 处理 数据 其他 包含 返回 MVC NET 文件 结果 ASP      更新时间:2023-09-26

我目前正在收集如何解决以下问题的想法:我正在实时生成报告并使用File方法将其返回到浏览器。

public ActionResult GenerateReport()
{
  var report = ... // Don't care, we get an object containing an Id and a byte array
  var reportId = report.Id; // this is actually important
  return File(report.Data, "..."); // Return data with some content type, filename etc.
}

执行操作时,浏览器将提示文件下载。但我也想以某种方式将新Id传输到我需要处理的浏览器。

你知道我如何使用通用的JavaScript(jQuery)和Web/ASP.NET/Ajax或任何技术来解决这个问题吗?

使用饼干!

在你的响应中添加一个cookie,然后有循环的jquery代码来查找它。在该 cookie 中,您可以添加 id 并在找到循环后停止循环。然后再次删除它。

例如,我使用下面的 ActionFilter 来检测文件何时被处理以供下载,就像您一样使用文件操作结果。

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var key = filterContext.HttpContext.Request.QueryString["downloading"].ToString();
        if (key != null)
        {
            var cookie = new HttpCookie(key);
            cookie.Path = "/";
            filterContext.HttpContext.Response.Cookies.Add(cookie);
        }
    }

我们最终得出的结果是,我们能够在后端进行更改,现在我们可以请求"临时"ID,而无需实际开始报告生成,而实际的报告生成现在需要提供ID。这是客户端现在的样子:

function generateReport() {
    $.ajax({
        url: "/GetNewReportId", // A) This is where we get the new ID
        method: 'POST'
    })
    .done(function (result) {
        if (result) {
            // The ID is returned here: result.Id
            // Open the confirmation modal with Id assigned
            showConfirmationModal(result.Id);
            // B) This will lead to a download-prompt and leave site functioning
            window.location = "/GenerateReport?id=" + resultId;
        }
    });
}

操作/GetNewReportId是一个简单的 Mvc 操作,返回一个 JsonResult,只包含 ID。此外,代码被简化以向您展示想法,它尚未以最终形式进行测试。

但也有一些缺点:如果过程在步骤 A) 和 B 之间的某个地方失败,您最终可能会有一些未处理 ID 的记录,您必须在某个时候清理这些记录。