无法通过iframe添加Cookie

时间:2014-10-28 16:32:59

标签: javascript c# iframe cookies asp.net-web-api

我正在动态创建一个带有表单的iframe并提交此表单:

var iframe = $("<iframe id='download_iframe' style='display: none' src='about:blank'></iframe>");
//...building that form...
form.appendTo( iframe.contents().find('body') ).submit();

在该请求所在的url处我正在生成一个文件并设置一个像这样的cookie:

HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
//...setting content type, disposition and etc...
response.Headers.AddCookies(new[]
                                    {
                                        new CookieHeaderValue("ajaxFileDownload", "true")
                                        {
                                            Expires = DateTimeOffset.Now.AddDays(1),
                                            Domain = Request.RequestUri.Host,
                                            Path = "/",
                                            HttpOnly = false
                                        }
                                    });

所以我希望在文件downlod启动后设置cookie,我可以在标题中看到Set-Cookie

Cache-Control:private
Content-Disposition:attachment; filename=engagement_list_28-10-2014.pdf
Content-Length:60027
Content-Type:application/pdf
Date:Tue, 28 Oct 2014 16:12:09 GMT
Expires:-1
Pragma:no-cache
Server:Microsoft-IIS/7.5
Set-Cookie:ajaxFileDownload=true; expires=Wed, 29 Oct 2014 16:59:35 GMT; domain=localhost; path=/
X-AspNet-Version:4.0.30319
X-MiniProfiler-Ids:["a8e9bef2-d31e-4f41-8896-9222d880544f"]
X-Powered-By:ASP.NET
X-Powered-By:ARR/2.5
X-Powered-By:ASP.NET

但是document.cookie$("#download_iframe").contents()[0].cookie是空的,我甚至无法在浏览器的资源中看到该Cookie。我做错了什么?

1 个答案:

答案 0 :(得分:0)

这可能是由创建从localhost以外的主机加载的iframe的页面引起的。正在为localhost创建cookie,如果您创建的HTML是从文件系统或其他主机加载的,那么您将无法看到cookie。

其他原因可能是

1)您的浏览器的Cookie政策。

2)浏览器运行的操作系统的时间。它是否大于Expires字段?

相关问题