【问题标题】:Reading Cookie Data from Different Subdomain从不同的子域读取 Cookie 数据
【发布时间】:2015-10-09 01:40:28
【问题描述】:

我有一个在 domain1.mywebsite.com 上创建 cookie 的 ASP.Net 应用程序。

Private Sub CreateCookie()
    If Request.Cookies("D1_MyWebSite") Is Nothing Then
        Dim aCookie As New HttpCookie("D1_MyWebSite")
        aCookie.Path = "/"
        aCookie.Value = DateTime.Now.ToUniversalTime.ToString
        aCookie.Expires = DateTime.Now.AddMinutes(10)
        Response.Cookies.Add(aCookie)
    Else
        Dim cookie As HttpCookie = HttpContext.Current.Request.Cookies("D1_MyWebSite")
        cookie.Value = DateTime.Now.ToUniversalTime.ToString
        cookie.Expires = DateTime.Now.AddMinutes(10)
        Response.Cookies.Add(cookie)
    End If
End Sub

在 domain2.mywebsite.com 上,我正在尝试使用 jQuery 读取保存在 cookie 中的值。 网页地址是 domain2.mywebsite.com/index.html 但我的 .js 文件的来源是:

<script type="text/javascript" src="https://domain1.mywebsite.com/js/jumppage.js"></script>
<script src="https://domain1.mywebsite.com/js/jquery.cookie.js"></script>

我尝试使用以下方法获取 domain1.mywebsite.com D1_MyWebSite cookie 的值,但它所做的只是为 domain2.mywebsite.com 创建一个名为 D1_MyWebSite 的新 cookie。如何获取 domain1.mywebsite.com D1_MyWebSiteCookie 的 cookie 值?

    $.cookie("D1_MyWebSite", "value");

【问题讨论】:

  • 更新:我已将 aCookie.Path = "/" 替换为 aCookie.Domain=".mywebsite.com"。现在我已经这样做了,它为 mywebsite.com 创建了一个 cookie,但我仍然无法使用 jQuery 访问它。我的 jQuery 代码继续为 domain2.mywebsite.com 创建一个 D1_MyWebSite cookie。

标签: javascript jquery asp.net vb.net cookies


【解决方案1】:

终于解决了问题。我必须删除 .Path 并添加 .Domain。

    Dim aCookie As New HttpCookie("D1_MyWebSite")
    aCookie.Domain = ".mywebsite.com"
    aCookie.Value = DateTime.Now.ToUniversalTime.ToString

我能够使用以下代码使用 jQuery 获取存储在 domain2 上的 cookie 中的日期时间值:

    var MyValue = $.cookie("D1_MyWebSite");

【讨论】:

    【解决方案2】:

    您必须将路径设置为“/”,如

    aCookie.Path = "/";
    

    【讨论】:

    • 对不起,“/”不知何故从原始帖子中删除了。我已经修正了错字。 aCookie.Path = "/" 似乎没有什么区别。
    猜你喜欢
    • 2016-07-19
    • 1970-01-01
    • 1970-01-01
    • 2011-04-03
    • 2012-06-25
    • 2015-05-24
    • 1970-01-01
    • 2014-09-01
    相关资源
    最近更新 更多