Example:
Copy codeThe Code is as follows:
Protected void Page_Load (object sender, EventArgs e)
{
If (! IsPostBack)
{
HttpCookie UserInfo = new HttpCookie ("UserInfo ");
UserInfo. Value = "bdstjk ";
Response. Cookies. Add (UserInfo );
}
}
Protected void btnRemoveCookie_Click (object sender, EventArgs e)
{
Response. Cookies. Remove ("UserInfo ");
Response. Write ("<script type = \" text/javascript \ "> alert (\" Cookie deleted successfully! \ "); </Script> ");
}
Protected void btnCheckCookie_Click (object sender, EventArgs e)
{
If (Request. Cookies ["UserInfo"]! = Null)
{
Response. Write ("Cookie exists," + Request. Cookies ["UserInfo"]. Value );
}
Else
{
Response. Write ("Cookie does not exist ");
}
}
Page code:
Copy codeThe Code is as follows:
<Asp: Button ID = "btnRemoveCookie" runat = "server" Text = "delete Cookie"
/>
<Asp: Button ID = "btnCheckCookie" runat = "server" Text = "Check Cookie"
/>
Run the code test and you will find that the delete button and cookie exist, such:
Why? The cookie deletion operation is clearly performed. why can't the cookie be deleted?
Let's take a look at the source code of. NET's HttpCookieCollection implementation.
Copy codeThe Code is as follows:
Public void Remove (string name)
{
If (this. _ response! = Null)
{
This. _ response. BeforeCookieCollectionChange ();
}
This. RemoveCookie (name );
If (this. _ response! = Null)
{
This. _ response. OnCookieCollectionChange ();
}
}
This operation deletes the cookie in the HttpCookieCollection set. When the Server transfers data to the client, it does not contain any information about the Cookie that has been deleted on the server, the browser will not make any changes to the cookie (the remove method only prevents the server from sending the deleted cookie to the client, and this cookie is not left in the client ). Therefore, the cookie cannot be deleted.
So what should we do if we want to delete the cookie?
Change the cookie deletion code to the following statement:
Copy codeThe Code is as follows:
If (Request. Cookies ["UserInfo"]! = Null)
{
Response. Cookies ["UserInfo"]. Expires = DateTime. Now. AddDays (-1 );
}
Response. Write ("<script type = \" text/javascript \ "> alert (\" Cookie deleted successfully! \ "); </Script> ");
Run the program again to test:
Okay. The Cookie has been deleted. Set the Cookie expiration time to negative to force the Cookie to expire. We can achieve what we need.
Since Response. cookies. there is no way to implement the effect we need to Remove. Why does Microsoft keep it? Because CookieCollection implements the ICollection interface, romove is a required method, although it has little practical value. The romove of the set should also be implemented in this way, but Microsoft did not clearly describe it when writing MSDN, which caused us a lot of trouble.