Examples are as follows:
Copy Code code 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 (\" Delete Cookie success!) \ ");</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 Code code as follows:
<asp:button id= "Btnremovecookie" runat= "server" text= "Delete Cookie"
/>
<asp:button id= "Btncheckcookie" runat= "Server" text= "Check Cookies"
/>
Run the code test, you will find out, how to click the Delete button, the cookie exists, the following figure:
What is this for? Clearly is the implementation of the deletion of cookies, why is not deleted?
Let's go and have a look. NET HttpCookieCollection realize the source code
Copy Code code 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 removes cookies from the HttpCookieCollection collection, and when the server transmits the data to the client, it does not contain any information about the cookie that has been removed from the service side. The browser will not make any changes to it (the Remove method simply does not allow the server to send the deleted cookie to the client and does not leave the cookie in the client). So the cookie does not drop out of the situation appears.
So what should we do if we want to delete cookies?
Change the code to delete the cookie to the following statement:
Copy Code code as follows:
if (request.cookies["UserInfo"]!= null)
{
response.cookies["UserInfo"]. Expires = DateTime.Now.AddDays (-1);
}
Response.Write ("<script type=\" text/javascript\ ">alert (\" Delete Cookie success!) \ ");</script>");
Let's run the program again and test:
All right. The cookie has been deleted. Force the cookie to expire by setting a negative expiration time for the cookie. Can achieve the effect we need.
Since Response.Cookies.Remove has no way to achieve the results we need, why Microsoft has left, because cookiecollection implement ICollection interface, Romove is the method that must be implemented, although it is not much practical value. And the collection of romove should be such a way to achieve, but Microsoft in the writing MSDN, the description is too unclear, causing us a lot of trouble.