98

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?

Jon Schneider
  • 25,758
  • 23
  • 142
  • 170
Karthik Malla
  • 5,570
  • 12
  • 46
  • 89

12 Answers12

168

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.

VMAtm
  • 27,943
  • 17
  • 79
  • 125
Kirill
  • 3,028
  • 1
  • 17
  • 18
  • 18
    `Session.Abandon` will clear the ASP.NET session cookie, but not cookies you set manually, like userID here. And `Cookies["whatever"]` is never null; the framework will create a cookie if you ask for a non-existent one. – Andomar Jul 09 '11 at 14:53
  • 16
    @Andomar, actually `Cookies["whatever"]`returns null when the cookie does not exist! I know this is an old comment but I dont want other readers being mislead by this comment. – Nuno Agapito Sep 30 '14 at 15:36
  • 8
    It's also very important that `Expires` is NOT set to `DateTime.MinValue` as this will actually give the cookie a Session expiration, which means it waits until the browser/tab (browser dependent) is closed before deleting the cookie. – Nashenas May 14 '15 at 22:18
  • 8
    @NunoAgapito Very old but for other users, Cookies["whatever"] returns null if you read from "Request" and return an empty cookie if you read from "Response". – Athiwat Chunlakhan Sep 06 '16 at 03:19
  • but this only removes the content from the cookie, the cookie still remains in the browser at least for me – Beingnin Oct 11 '17 at 12:09
55

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
VMAtm
  • 27,943
  • 17
  • 79
  • 125
  • Right about the expiry date, but I believe the `if` line doesn't actually work. When you ask for a cookie with `Cookies["whatever"]` the framework will create a cookie if it doesn't exist. – Andomar Jul 09 '11 at 14:56
  • @Andomar This code I got from MSDN. I don't think that it will create a cookie if we call `Request` object. – VMAtm Jul 09 '11 at 14:59
  • 2
    Aha, looks like it only creates a cookie for the `Response` object. Interesting :) – Andomar Jul 09 '11 at 15:06
  • 3
    This code can be optimized just in one line `Response.Cookies["UserSettings"].Expires = DateTime.Now.AddDays(-1)`. Here server will request browser to remove cookie. Browser will remove it if it exists. – shashwat Sep 01 '13 at 05:53
  • @harsh This code is a stub, so you can use it as you wish. Still you should check the cookie for existence to lower unnessessary work. – VMAtm Sep 01 '13 at 21:53
  • 2
    Yeah for me I needed the Response.Cookies.Add(myCookie) part - without it it doesn't work always/correctly. Thanks. – Christopher Jan 07 '16 at 12:21
  • What if I first need to delete the cookie value, then add a new value for the same cookie? – serge Jan 29 '16 at 14:30
  • @Serge You can simply override the value with the new one, if cookie exists, and simply add a new one if there is no of it on client. – VMAtm Jan 29 '16 at 14:42
  • I observed that I have multiples values for my site, having different paths, it confusing, so decided to delete (all) and then crete new one... – serge Jan 29 '16 at 16:21
  • @Serge You can erase then one one page and after that move u ser to other page and recreate the cookies. – VMAtm Jan 29 '16 at 21:46
  • foreach(HttpCookie c in Request.Cookies) { Response.Cookies[c.Name].Expires = DateTime.Now.AddDays(-1); } – Mukesh Agarwal Feb 27 '19 at 13:00
34

This is what I use:

    private void ExpireAllCookies()
    {
        if (HttpContext.Current != null)
        {
            int cookieCount = HttpContext.Current.Request.Cookies.Count;
            for (var i = 0; i < cookieCount; i++)
            {
                var cookie = HttpContext.Current.Request.Cookies[i];
                if (cookie != null)
                {
                    var expiredCookie = new HttpCookie(cookie.Name) {
                        Expires = DateTime.Now.AddDays(-1),
                        Domain = cookie.Domain
                    };
                    HttpContext.Current.Response.Cookies.Add(expiredCookie); // overwrite it
                }
            }

            // clear cookies server side
            HttpContext.Current.Request.Cookies.Clear();
        }
    }
thomasb
  • 5,816
  • 10
  • 57
  • 92
Michael Kang
  • 52,003
  • 16
  • 103
  • 135
12

Unfortunately, for me, setting "Expires" did not always work. The cookie was unaffected.

This code did work for me:

HttpContext.Current.Session.Abandon();
HttpContext.Current.Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));

where "ASP.NET_SessionId" is the name of the cookie. This does not really delete the cookie, but overrides it with a blank cookie, which was close enough for me.

Buh Buh
  • 7,443
  • 1
  • 34
  • 61
6

In ASP.NET Core, there is a straight forward built in function. To delete a cookie try this code:

if(Request.Cookies["aa"] != null)
{
    Response.Cookies.Delete("aa");
}
return View();
Said Al Souti
  • 305
  • 4
  • 13
5

I just want to point out that the Session ID cookie is not removed when using Session.Abandon as others said.

When you abandon a session, the session ID cookie is not removed from the browser of the user. Therefore, as soon as the session has been abandoned, any new requests to the same application will use the same session ID but will have a new session state instance. At the same time, if the user opens another application within the same DNS domain, the user will not lose their session state after the Abandon method is called from one application.

Sometimes, you may not want to reuse the session ID. If you do and if you understand the ramifications of not reusing the session ID, use the following code example to abandon a session and to clear the session ID cookie:

Session.Abandon();
Response.Cookies.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.

http://support.microsoft.com/kb/899918

MTs
  • 514
  • 5
  • 13
4

You should never store password as a cookie. To delete a cookie, you really just need to modify and expire it. You can't really delete it, ie, remove it from the user's disk.

Here is a sample:

HttpCookie aCookie;
    string cookieName;
    int limit = Request.Cookies.Count;
    for (int i=0; i<limit; i++)
    {
        cookieName = Request.Cookies[i].Name;
        aCookie = new HttpCookie(cookieName);
        aCookie.Expires = DateTime.Now.AddDays(-1); // make it expire yesterday
        Response.Cookies.Add(aCookie); // overwrite it
    }
Rajamohan Anguchamy
  • 1,726
  • 1
  • 17
  • 35
3

Taking the OP's Question title as deleting all cookies - "Delete Cookies in website"

I came across code from Dave Domagala on the web somewhere. I edited Dave's to allow for Google Analytics cookies too - which looped through all cookies found on the website and deleted them all. (From a developer angle - updating new code into an existing site, is a nice touch to avoid problems with users revisiting the site).

I use the below code in tandem with reading the cookies first, holding any required data - then resetting the cookies after washing everything clean with the below loop.

The code:

int limit = Request.Cookies.Count; //Get the number of cookies and 
                                   //use that as the limit.
HttpCookie aCookie;   //Instantiate a cookie placeholder
string cookieName;   

//Loop through the cookies
for(int i = 0; i < limit; i++)
{
 cookieName = Request.Cookies[i].Name;    //get the name of the current cookie
 aCookie = new HttpCookie(cookieName);    //create a new cookie with the same
                                          // name as the one you're deleting
 aCookie.Value = "";    //set a blank value to the cookie 
 aCookie.Expires = DateTime.Now.AddDays(-1);    //Setting the expiration date
                                                //in the past deletes the cookie

 Response.Cookies.Add(aCookie);    //Set the cookie to delete it.
}

Addition: If You Use Google Analytics

The above loop/delete will delete ALL cookies for the site, so if you use Google Analytics - it would probably be useful to hold onto the __utmz cookie as this one keeps track of where the visitor came from, what search engine was used, what link was clicked on, what keyword was used, and where they were in the world when your website was accessed.

So to keep it, wrap a simple if statement once the cookie name is known:

... 
aCookie = new HttpCookie(cookieName);    
if (aCookie.Name != "__utmz")
{
    aCookie.Value = "";    //set a blank value to the cookie 
    aCookie.Expires = DateTime.Now.AddDays(-1);   

    HttpContext.Current.Response.Cookies.Add(aCookie);    
}
Martin Sansone - MiOEE
  • 4,281
  • 1
  • 29
  • 31
1

Though this is an old thread, i thought if someone is still searching for solution in the future.

HttpCookie mycookie = new HttpCookie("aa");
mycookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(mycookie1);

Thats what did the trick for me.

Ahsan
  • 33
  • 8
1

I strongly preferer this if anyone like it.

string COOKIE_NAME = "COOCKIE NAME"

if (HttpContext.Request.Cookies.AllKeys.Contains(COOKIE_NAME))
        {
            HttpCookie Cookie = HttpContext.Request.Cookies[COOKIE_NAME];
            engagementIdCookie.Expires = DateTime.Now.AddDays(-1);
            Response.Cookies.Add(Cookie);
        }
Kd Nimavat
  • 282
  • 1
  • 11
0

Response.Cookies["UserSettings"].Expires = DateTime.Now.AddDays(-1)

Noman Chali
  • 330
  • 3
  • 15
0

You have to set the expiration date to delete cookies

Request.Cookies[yourCookie]?.Expires.Equals(DateTime.Now.AddYears(-1));

This won't throw an exception if the cookie doesn't exist.

baltermia
  • 1,151
  • 1
  • 11
  • 26