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);
Pingback: Streaming objects into a cookie « Brian Pedersen’s Sitecore and .NET Blog
Brian..thanks for sharing this article…I have question related to Sitecore and cookies. When we see our cookies of our website, developed in sitecore, we found out that there is a cookie by name “sc_pview_shuser=;”. Do you know the reason of this being created by Sitecore or have any idea how can I remove this cookie or make this cookie as a secured cookie?
Thanks for your help
LikeLike
This cookie is generated when previewing a web page by the Sitecore.Publishing.PreviewProvider and is used to remember your preview and debug settings.
To avoid having such a cookie, you could consider having a staged environment where your editor server is not the same as your web server. The cookie is only written when previewing and debugging.
LikeLike
Brian…Thanks for your suggestion. In addition to your notes I want to add that this cookie is also added by SEO Toolkit module. This was happening in our case and we solved the issue.
LikeLike