So I have a problem with a cookie not setting after returning a File only happening in IE.
The logic is as follows:
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?
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)
});