C# and Cookie subitems

joe_pool_is

Contributor
Joined
Jan 18, 2004
Messages
507
Location
Longview, TX [USA]
Someone please show me how to *create* subitems (or subkeys) for my cookies. I have found code out there for doing this in VB.NET, but I can not seem to get it to work in C#. Here is what I have:
Code:
void Page_Load(Object Sender, EventArgs e) {
  HttpCookie cookie = Request.Cookies["userCookie"];
  if (cookie == null) {
	cookie = new HttpCookie("userInfo");
	cookie.HasKeys = true; // this bombs: HasKeys is read only
	cookie.Value["userInfo"]["userName"] = "jdoe"; // this bombs. Why?
	cookie.Value["realName"] = "John Doe"; // this bombs, too. Why?
	cookie.Value["lastVisit"] = DateTime.Now.ToString; // can't get this far
	cookie.Expires = DateTime.Now.AddDays(365);
	cookie.Path = Server.MapPath("/");
	Response.Cookies.Add(cookie);
  }
}
 
Okay, I got this to work:
Code:
void Page_Load(Object Sender, EventArgs e) {
HttpCookie cookie = Request.Cookies["userCookie"];
if (cookie == null) {
	cookie = new HttpCookie("userInfo");
	cookie.Values.Add("userName", "jdoe");
	cookie.Values.Add("realName", "John Doe");
	cookie.Values.Add("lastVisit", DateTime.Now.ToString());
	cookie.Expires = DateTime.Now.AddDays(365);
	cookie.Path = Server.MapPath("/");
	Response.Cookies.Add(cookie);
} else {
	if (cookie.Value.ToString() == "") {
	loginPanel.Visible = true;
	} else {
	 // if userInfo is found in the database 
	 welcomeName.Text = "Welcome back " + cookie["realName"].ToString();
	 welcomePanel.Visible = true;
	}
}
}

Just posting this to help others that might browse here looking for solutions.
 
Back
Top