Creating cookies is no problem:
// Create the cookie HttpCookie cookie = new HttpCookie("MyCookie", "MyValue"); // Let the cookie expire in 1 year cookie.Expires = DateTime.Now.AddYears(1); // Add the cookie to the response header HttpContext.Current.Response.Cookies.Add(cookie);
But have you ever tried to remove a cookie, but nothing happens? It seemes that the “Remove” have no effect:
//Why does this not remove my cookie? HttpContext.Current.Request.Cookies.Remove("MyCookie");
Setting a cookie is a dialog between the client and server. Adding a cookie is done by adding it to the response header. It is the client (IE, FIrefox, Opera) who will write the cookie, usually to disk.
Next time the client requests a page from the domain, any un-expired cookies is written to the request headers, where you can read the information from within client side code.
Removing the cookie with Request.Cookies.Remove() only removes the cookie from the request collection, not from disk.
Instead you can let the cookie expire. The client will then leave the cookie when requesting a page from your domain:
// Find the cookie HttpCookie cookie = HttpContext.Current.Request.Cookies["MyCookie"]; // If found, let the cookie expire if (cookie != null) cookie.Expires = DateTime.Now.AddYears(-1);