Add and Remove cookies

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

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?

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

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in General .NET and tagged , , . Bookmark the permalink.

4 Responses to Add and Remove cookies

  1. Pingback: Streaming objects into a cookie « Brian Pedersen’s Sitecore and .NET Blog

  2. vamshik says:

    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

  3. briancaos says:

    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.

  4. vamshik says:

    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.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s