Abhishek
Abhishek

Reputation: 173

how to delete external site cookies through C# code

I have a authentication page for windows azure authentication where authentication is performed on https://login.microsoftonline.com/login.srf?wa=wsignin1.0&wtrealm=........ and after successful authentication we are redirecting to our site.

We need to delete cookies generated on this url for logout. can any body provide me the code through which we can delete external site cookies.

We have tried to delete using the following code but could not get success.

public void deleteallcookies()
{
    int limit = Request.Cookies.Count; 
    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);    
         aCookie.Value = "";    //set a blank value to the cookie 
        aCookie.Expires = DateTime.Now.AddDays(-1);    

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

Upvotes: 3

Views: 1578

Answers (1)

dove
dove

Reputation: 20692

You want to get the cookie from the Response not the Request, i.e.

cookieName = Response.Cookies[i].Name; 

you can also enumerate slightly more elegantly as follows:

string[] myCookies = HttpContext.Current.Request.Cookies.AllKeys;
foreach (string cookieName in myCookies)
{
      var cookie = HttpContext.Current.Response.Cookies[cookieName];
      if (cookie != null)
      {
            cookie.Value = "";
            cookie.Expires = DateTime.Now.AddDays(-1);
      }
}

Upvotes: 2

Related Questions