How to Delete a Previously Created Cookie With C# ASP.Net / Deleting Cookie ASP.Net

You created a cookie on you asp.net forms application now you would like to delete it. This quick article show how to do the trick...
3 October 2010
1 minutes read

Related Posts

I am sure that you leave cookies into client computer on purpose or without knowing if you're an asp.net developer. Also if you create a sales website, there must be steps on this sales applicatiion and you should get the data from a previous page to another pages. The best way is always cookie if the information is not so sensetive. 

But what if we wanna delete them ? It is not as simple as creating them (essentially it is but not by directly deleting it) We cannot directly delete a file from user's computer. So what will we do? 

I assume there are another ways but the one way is setting the expiry date on a previous date. Here is the example;

 

if (Request.Cookies["UserSettings"] != null) {

    HttpCookie myCookie = new HttpCookie("UserSettings");
    //Here, we are setting the time to a previous time.
    //When the browser detect it next time, it will be deleted automatically.
    myCookie.Expires = DateTime.Now.AddDays(-1d);
    Response.Cookies.Add(myCookie);

} 

 

Hope this helps :)