How to delete cookies on an ASP.NET website

后端 未结 11 2078
傲寒
傲寒 2020-11-30 05:07

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 co

11条回答
  •  温柔的废话
    2020-11-30 05:56

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

提交回复
热议问题