Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete cookies on an ASP.NET website

In my website when the user clicks on the "Logout" button, the Logout.aspx page loads with code Session.Clear().

In ASP.NET/C#, does this clear all cookies? Or is there any other code that needs to be added to remove all of the cookies of my website?

like image 206
Karthik Malla Avatar asked Jul 09 '11 14:07

Karthik Malla


People also ask

How do I delete cookies in net?

Cookies cannot be deleted or removed, it can be made to expire by setting its Expiry Date to a Past Date in ASP.Net MVC Razor. Note: For beginners in ASP.Net MVC, please refer my article ASP.Net MVC Hello World Tutorial with Sample Program example.

How do I delete cookies in VB net?

You cannot directly delete a cookie on a user's computer. However, you can direct the user's browser to delete the cookie by setting the cookie's expiration date to a past date.

Which method is used to delete a cookie?

Deleting Cookie: There is no special dedicated function provided in PHP to delete a cookie. All we have to do is to update the expire-time value of the cookie by setting it to a past time using the setcookie() function. A very simple way of doing this is to deduct a few seconds from the current time.

Does ASP.NET session use cookies?

Yes, by default ASP.NET Session use cookies.


2 Answers

Try something like that:

if (Request.Cookies["userId"] != null) {     Response.Cookies["userId"].Expires = DateTime.Now.AddDays(-1);    } 

But it also makes sense to use

Session.Abandon(); 

besides in many scenarios.

like image 120
Kirill Avatar answered Oct 22 '22 15:10

Kirill


No, Cookies can be cleaned only by setting the Expiry date for each of them.

if (Request.Cookies["UserSettings"] != null) {     HttpCookie myCookie = new HttpCookie("UserSettings");     myCookie.Expires = DateTime.Now.AddDays(-1d);     Response.Cookies.Add(myCookie); } 

At the moment of Session.Clear():

  • All the key-value pairs from Session collection are removed. Session_End event is not happen.

If you use this method during logout, you should also use the Session.Abandon method to Session_End event:

  • Cookie with Session ID (if your application uses cookies for session id store, which is by default) is deleted
like image 30
VMAtm Avatar answered Oct 22 '22 16:10

VMAtm