Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete cookie from .Net [duplicate]

Tags:

c#

.net

cookies

Possible Duplicate:
Delete cookie on clicking sign out

I want to delete cookies when the user logout.

Here is my code:

 if (HttpContext.Current.Request.Cookies["currentUser"] != null)  {      DeleteCookie(HttpContext.Current.Request.Cookies["currentUser"]);  }          public void DeleteCookie(HttpCookie httpCookie)         {             try             {                 httpCookie.Value = null;                 httpCookie.Expires = DateTime.Now.AddMinutes(-20);                 HttpContext.Current.Request.Cookies.Add(httpCookie);             }             catch (Exception ex)             {                 throw (ex);             }         } 

But it doesn't work. Do you have any suggestion?

like image 989
cagin Avatar asked Aug 24 '12 20:08

cagin


People also ask

How do I remove cookies from code?

Delete a Cookie with JavaScript Just set the expires parameter to a past date: document. cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; You should define the cookie path to ensure that you delete the right cookie.

How do you delete multiple cookies?

Delete browser cache and cookies in ChromeOpen Google Chrome. Click the menu button ⋮ > More Tools > Clear browsing data. On the Clear browsing data window, select which time range you want to clear. Put a check beside Cookies and other site data and Cached images and files, and then click Clear data.

Can I delete cookie from another domain?

For security, you're not allowed to edit (or delete) a cookie on another site.

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.


2 Answers

 HttpCookie currentUserCookie = HttpContext.Current.Request.Cookies["currentUser"];  HttpContext.Current.Response.Cookies.Remove("currentUser");  currentUserCookie.Expires = DateTime.Now.AddDays(-10);  currentUserCookie.Value = null;  HttpContext.Current.Response.SetCookie(currentUserCookie); 

It works.

like image 116
cagin Avatar answered Oct 04 '22 16:10

cagin


Instead of adding the cookie, you should change the Response's cookies Expires to a value in the past:

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

Sidenote: Instead of throw ex you should just throw it to keep its stacktrace. C#: Throwing Custom Exception Best Practices

like image 29
Tim Schmelter Avatar answered Oct 04 '22 15:10

Tim Schmelter