Search code examples
.netfileinternet-explorercookiesactionresult

IE doesn't set cookie when return File() from ActionResult


So I have a problem with a cookie not setting after returning a File only happening in IE.

The logic is as follows:

  1. When use first visits the page they are returned a View
  2. User submits the form and a document is generated
    2.a. If the generation of the file succeeds: it returns a file for the user to download.
    2.b. If the generation of the file fails: it returns an error message.

In both cases of 2: the page should show a message because of a cookie being set - however it only shows a message when the file fails and not when it returns a file for download.

My code looks something like this:

public ActionResult MyAction(string parm) {
    if (parm != null) {
        // generate file and message
        byte[] generatedFile = GenerateCsvFile(parm, out bool success, out string message);

        // Set cookie with message saying it failed or succeeded
        Response.Cookies.Add(new HttpCookie("downloadedFile", message) {
            Expires = DateTime.Now.AddSeconds(60)
        });

        if (success) { // return file for user to download
            return File(generatedFile, "text/csv", "MyDocument.csv");
        }
        return new HttpStatusCodeResult(204); // do nothing because it failed
    }

    // Initial view load
    return View();
}

What is happening here and how do I fix it?


Solution

  • The result message when a file was returned included characters that were invalid to put into a cookie readable by IE (but readable by Chrome, Firefox etc).
    Therefore the fix was to URL encode it before setting it as the cookie.

    Response.Cookies.Add(
        new HttpCookie("downloadedFile", System.Web.HttpUtility.UrlEncode(message)) {
            Expires = DateTime.Now.AddSeconds(60)
        });