This article describes how to write, read, modify, and delete cookies in asp.net c #. For more information, see.
// Write cookie
The Code is as follows: |
Copy code |
HttpCookie cookie = new HttpCookie ("Info"); // defines the cookie object and the item named Info. Cookie. Expires = DateTime. Now. AddDays (1); // The valid time for adding a cookie is one day. Cookie. Values. Add ("user", "cxbkkk"); // Add attributes Cookie. Values. Add ("userid", "1203 "); Response. AppendCookie (cookie); // confirm that the cookie is being written. // Read cookie If (Request. Cookies ["Info"]! = Null) { String temp = Convert. toString (Request. cookies ["Info"]. values ["user"]) + "" + Convert. toString (Request. cookies ["Info"]. values ["userid"]); // Use Request. Cookies ["Info"]. Value to read all data) If (temp = "") { Response. Write ("null "); } Else Response. Write (temp ); } Else { Response. Write ("error "); } |
// Modify the Cookie
The Code is as follows: |
Copy code |
Protected void Button3_Click (object sender, EventArgs e) { // Obtain the Cookie object of the Client HttpCookie cok = Request. Cookies ["MyCook"];
If (cok! = Null) { // Two methods for Cookie Modification Cok. Values ["userid"] = "alter-value "; Cok. Values. Set ("userid", "alter-value "); // Add new content to the Cookie Cok. Values. Set ("newid", "newValue "); Response. AppendCookie (cok ); } }
|
// Delete the attributes under the cookie
The Code is as follows: |
Copy code |
Var acookie = Request. Cookies ["Info"]; Acookie. Values. Remove ("userid "); Acookie. Expires = DateTime. Now. AddDays (1 ); Response. Cookies. Add (acookie ); |
// Delete all cookies, that is, set the expiration time to now.
Request. Cookies. Clear () is not used to delete Cookies.
Deleting a Cookie (that is, physically removing a Cookie from a user's hard disk) is a form of Cookie modification.
The Cookie cannot be directly removed because it is on the user's computer.
However, the browser can delete cookies for you.
This technology creates a new Cookie with the same name as the Cookie to be deleted,
Set the Cookie expiration date to a date earlier than the current date.
When the browser checks the Cookie expiration date, the browser will discard the expired Cookie.
The following code example demonstrates how to delete all available cookies in an application:
The Code is as follows: |
Copy code |
HttpCookie aCookie; String cookieName; Int limit = Request. Cookies. Count; For (int I = 0; I <limit; I ++) { CookieName = Request. Cookies [I]. Name; ACookie = new HttpCookie (cookieName ); ACookie. Expires = DateTime. Now. AddDays (-1 ); Response. Cookies. Add (aCookie ); } |