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.
![]() |
---|
Calling the |
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.
Visual BasicВ Copy Code
If (Not Request.Cookies("UserPreferences1") Is Nothing) Then Dim myCookie As HttpCookie myCookie = New HttpCookie("UserPreferences1") myCookie.Expires = DateTime.Now.AddDays(-1D) Response.Cookies.Add(myCookie) End If
C#В Copy Code
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 topic
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
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