访问在一个子域上创建的 Cookie 在另一个子域上

本文关键字:创建 Cookie 另一个 一个 访问 | 更新日期: 2023-09-27 18:34:23

给定:

Domain 1: subdomain1.mydomain.com
Domain 2: subdomain2.mydomain.com

我使用以下代码在"域 1"上创建一个 cookie,并尝试访问"域 2"上的 cookie。

我的问题是"域 2"不想识别 cookie。什么给?我认为问题出在.域属性,但我把句号放在前面,所以我错过了什么?

public void CreateCookie()
{
    Boolean bNew = false;
    HttpCookie oCookie = HttpContext.Current.Request.Cookies.Get("myData");
    if (null == oCookie)
    {
        oCookie = new HttpCookie("myData");
        bNew = true;
    }
    // Set the cookie value.
    oCookie.Domain = ".mydomain.com";
    oCookie.Secure = false;
    oCookie["myid"] = "myid@whatever";
    oCookie.Expires = DateTime.Now.AddDays(7);
    if (true == bNew)
        HttpContext.Current.Response.Cookies.Add(oCookie);
    else
        HttpContext.Current.Response.Cookies.Set(oCookie);
}
public String GetCookie()
{
    String myid = null;
        HttpCookie oCookie = HttpContext.Current.Request.Cookies.Get("myData");
        if (null != oCookie)
        myid = HttpContext.Current.Server.HtmlEncode(oCookie["myid"]);
    return myid;
}

思潮?

访问在一个子域上创建的 Cookie 在另一个子域上

我做了更多的研究,我在另一张 stackoverflow.com 票上找到了答案,见这里。

基本上,代码更改是:

oCookie.Domain = "mydomain.com";
oCookie.Path = "/";
  1. 域名前没有句点。
  2. 添加值为"/"的路径属性。