Search This Blog

Saturday, October 13, 2007

ASP.NET Cookies

Cookies is Domain dependent. Cookies created under subdomain beta.mydomain.com will not able to retrive when access to www.mydomain.com. To ensure that we can retrive the same cookies, we need to specify the domain
For example, we want to write the information to cookies under mydomain when we access to url beta.mydomain.com

HttpCookie cook = new HttpCookie("mydomain");
Response.Cookies.Clear();
Response.Cookies.Add(cook);
cook["UserId"] = userId;
cook["Name"] = username.Text;
cook.Expires = DateTime.MaxValue;
Response.Cookies.Add(cook);

To retrive the cookies information:

if (Request.Cookies["mydomain"] != null)
{
if (Request.Cookies["mydomain"]["UserId"] != null && Request.Cookies["mydomain"]["Name"] != null)
{
Session["UserId"] = Convert.ToInt32(Request.Cookies["mydomain"]["UserId"].ToString());
Session["UserName"] = Request.Cookies["mydomain"]["Name"].ToString();
}
}

No comments: