How to: Delete a Cookie
You cannot directly delete a cookie on a user's computer. However, you can direct the user's browser to delete the cookie by setting the cookie's expiration date to a past date. The next time a user makes a request to a page within the domain or path that set the cookie, the browser will determine that the cookie has expired and remove it.
Note
Calling the Remove method of the Cookies collection removes the cookie from the collection on the server side, so the cookie will not be sent to the client. However, the method does not remove the cookie from the client if it already exists there.
To assign a past expiration date on a cookie
Determine whether the cookie exists, and if so, create a new cookie with the same name.
Set the cookie's expiration date to a time in the past.
Add the cookie to the Cookies collection object.
The following code example shows how to set a past expiration date on a cookie.
If (Not Request.Cookies("UserSettings") Is Nothing) Then Dim myCookie As HttpCookie myCookie = New HttpCookie("UserSettings") myCookie.Expires = DateTime.Now.AddDays(-1D) Response.Cookies.Add(myCookie) End If
if (Request.Cookies["UserSettings"] != null) { HttpCookie myCookie = new HttpCookie("UserSettings"); myCookie.Expires = DateTime.Now.AddDays(-1d); Response.Cookies.Add(myCookie); }
Compiling the Code
This example requires:
An ASP.NET Web page.
A cookie written previously named UserSettings, as illustrated in the topicHow to: Write a Cookie.
Robust Programming
For security reasons, you can read only cookies that are set by pages that are part of the same domain. If the cookie's Path property has been set, that cookie is also available only to pages and subfolders within that path of the domain.
When reading specific cookie values, test that the cookie exists and that it has a value, otherwise an exception will occur.
Security
The browser can send the data back only to the server that originally created the cookie. However, malicious users can access cookies and read their contents. Do not store sensitive information in a cookie, such as a user name or password. Instead, store a token that you can use to look up the sensitive information on the server. Additionally, cookies can be tampered with, so any data in cookie should be treated with the same measures you use to prevent cross site scripting attacks. See How to: Protect Against Script Exploits in a Web Application by Applying HTML Encoding to Strings for more information.