Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you clear cookies using asp.net mvc 3 and c#?

Ok, so I really think I am doing this right, but the cookies aren't being cleared.

 Session.Clear();  HttpCookie c = Request.Cookies["MyCookie"];  if (c != null)  {      c = new HttpCookie("MyCookie");      c["AT"] = null;      c.Expires = DateTime.Now.AddDays(-1);      Request.Cookies.Add(c);  }   return RedirectToAction("Index", "Home"); 

When the redirect happens, it finds the cookie again and moves on as though I never logged out. Any thoughts?

like image 453
David Avatar asked Feb 25 '11 20:02

David


People also ask

How should we remove cookies in asp net?

Add(new HttpCookie("ASP. NET_SessionId", "")); This code example clears the session state from the server and sets the session state cookie to null. The null value effectively clears the cookie from the browser.

How cookies works in ASP NET MVC?

In ASP.Net MVC application, a Cookie is created by sending the Cookie to Browser through Response collection (Response. Cookies) while the Cookie is accessed (read) from the Browser using the Request collection (Request. Cookies).

What is cookies in asp net c#?

A cookie is a small bit of text that accompanies requests and pages as they go between the Web server and browser. The cookie contains information the Web application can read whenever the user visits the site.

Where are cookies stored C#?

Cookies is a small piece of information stored on the client machine. This file is located on client machines "C:\Document and Settings\Currently_Login user\Cookie" path. Its is used to store user preference information like Username, Password,City and PhoneNo etc on client machines.


1 Answers

You're close. You'll need to use the Response object to write back to the browser:

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

More information on MSDN, How to: Delete a Cookie.

like image 75
Metro Smurf Avatar answered Oct 09 '22 18:10

Metro Smurf