简体   繁体   中英

How to pass cookies back from an ASP.NET Core App

I have the following method in an ASP.NET Core application which generates a file and returns the file.

  [HttpPost]
    public ActionResult Export(string data)
    {
        if (string.IsNullOrEmpty(data)) return View();

        const string contentType = "Application/msexcel";
        var fileName = "Export On " + DateTime.Now.ToString("MM-dd-yyyy hh:mm") + ".xlsx";
        var ms = ExportControllerService.Export(data, ref fileName, User.Identity.Name);

        var file = File(ms, contentType, fileName);
        var result = (ActionResult) file;
        return ms != null ? result : View();
    }

What I want to do is also pass back a cookie with this file. In a previous version of ASP.NET I did something like the following

            var result = workbook.SaveAsActionResult(string.Format("export-{0}.xlsx", DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss")), HttpContext.ApplicationInstance.Response,
                ExcelDownloadType.PromptDialog, ExcelHttpContentType.Excel2010);
            result.Response.SetCookie(new HttpCookie(ExportHelpers.DownloadCookieName, "true") { Path = "/" });

Notice that I'm taking the ActionResult that gets generated and messing with the response property to set the cookie.

To give you the full background what I'm doing is on a page I have a hidden IFrame, when this Export method is called what I do is post back the hidden IFrame, which calls this method and then once it finishes it displays the file open/download on the client, leaving the screen intact. The reason that I want to have this cookie is that while it is exporting I'm displaying a statusbar on the screen and I need to know when the file has finished generating and is ready to be open on the client, so that I hide that statusbar.

I think you will know the file has finished exporting and is ready to be downloaded by the fact that the POST has finished executing. I don't see a need to put this kind of information in a cookie. Cookies should be used for storing information about a user you need to persist between page loads or site visits.

ETA: You may want to put up your front-end code, since that seems to be where the problem is.

我可以将其与以下代码一起使用:HttpContext.Response.Cookies.Append(“ CranalyticsExportStatus‌``,” ExportComplete“);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM