Delete Cookie by setting the date of Expires : Delete « Cookie « ASP.NET Tutorial






<%@ Page %>
<script language="C#" runat="server">
private void Page_Init(object sender, EventArgs e)
{
  if((Request.Cookies["UserName"] != null) && 
    (Request.Cookies["UserName"].Value != null)) 
  UserNameLabel.Text = Request.Cookies["UserName"].Value.ToString();
}

private void SaveButton_Click(object sender, System.EventArgs e)
{
  Response.Cookies["UserName"].Value = UserNameTextBox.Text;
  if(PersistCookieCheckBox.Checked)
    Response.Cookies["UserName"].Expires = System.DateTime.Now.AddDays(1); 
  UserNameLabel.Text = UserNameTextBox.Text; 
}
private void DeleteButton_Click(object sender, System.EventArgs e)
{
  Response.Cookies["UserName"].Expires = System.DateTime.Now.AddDays(-1);
}
</script>
<html>
  <body>
    <form id="form1" method="post" runat="server">
      
        Update UserName in Cookie:
        <asp:TextBox id="UserNameTextBox" runat="server"></asp:TextBox>
        <asp:Button id="SaveButton" runat="server" Text="Save" OnClick="SaveButton_Click"></asp:Button>
        <asp:CheckBox id="PersistCookieCheckBox" runat="server" text="Persist Cookie?"></asp:CheckBox>
      
      
        Current Cookie Contents:
        <br>
        <asp:Label ID="UserNameLabel" Runat="server" EnableViewState="False"></asp:Label>
        <br>
        <asp:Button id="RefreshButton" runat="server" Text="Refresh Without Saving"></asp:Button>
        
        Deleting the cookie will take effect on the *next* postback, since the cookie information is still in Request.Cookies for the
        duration of the PostBack once the Delete button is clicked.  Click it once, then click the "Refresh Without Saving" button.
        
        <asp:Button id="DeleteButton" runat="server" Text="Delete Cookie" OnClick="DeleteButton_Click"></asp:Button>
      
    </form>
  </body>
</html>








12.2.Delete
12.2.1.Deleting Cookies
12.2.2.Delete All Cookies
12.2.3.Delete Cookie by setting the date of Expires