Accessing a cookie created on one subdomain on another subdomain
Asked Answered
L

1

8

Given:

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

I create a cookie on "Domain 1" using the code below and trying to access the cookie on "Domain 2".

My problem is that "Domain 2" does not want to recognize the cookie. What gives? I figure the problem is with the .Domain property, but I put the period before, so what am I missing?

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;
}

Thoughts?

Limburg answered 7/10, 2013 at 23:33 Comment(0)
L
8

I did some more research and I found the answer on another stackoverflow.com ticket, see here.

Basically, the code changes are:

oCookie.Domain = "mydomain.com";
oCookie.Path = "/";
  1. No period before the domain name.
  2. Add in a path property with the value of "/".
Limburg answered 8/10, 2013 at 0:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.