[c#] 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?

This question is related to c# asp.net session cookies session-cookies

The answer is


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


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
    }

It is 2018 now, so 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();

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.


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

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.


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();
        }
    }

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


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);    
}

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.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to session

What is the best way to manage a user's session in React? Spring Boot Java Config Set Session Timeout PHP Unset Session Variable How to kill all active and inactive oracle sessions for user Difference between request.getSession() and request.getSession(true) PHP - Session destroy after closing browser Get Current Session Value in JavaScript? Invalidating JSON Web Tokens How to fix org.hibernate.LazyInitializationException - could not initialize proxy - no Session How can I get session id in php and show it?

Examples related to cookies

SameSite warning Chrome 77 How to fix "set SameSite cookie to none" warning? Set cookies for cross origin requests Make Axios send cookies in its requests automatically How can I set a cookie in react? Fetch API with Cookie How to use cookies in Python Requests How to set cookies in laravel 5 independently inside controller Where does Chrome store cookies? Sending cookies with postman

Examples related to session-cookies

Invalidating JSON Web Tokens PHP session lost after redirect How to use cURL to send Cookies? Using Python Requests: Sessions, Cookies, and POST What is the difference between server side cookie and client side cookie? Check if cookies are enabled How to delete cookies on an ASP.NET website What is the difference between Sessions and Cookies in PHP? How to secure the ASP.NET_SessionId cookie?