4

Tried

 if (Request.Cookies["IsGuest"] != null)
     {
       Response.Cookies["IsGuest"].Expires = DateTime.Now.AddDays(-1);
       //HttpCookie myCookie = new HttpCookie("IsGuest");
       //myCookie.Expires = DateTime.Now.AddDays(-1d);
       //Response.Cookies.Add(myCookie);
     }
    string a = Request.Cookies["IsGuest"].Value;

and also tried by commenting uncommented code and uncommenting commented code but

 string a = Request.Cookies["IsGuest"].Value;

Always running and Request.Cookies["IsGuest"] is never null

Imad
  • 7,126
  • 12
  • 55
  • 112
  • http://stackoverflow.com/questions/6635349/how-to-delete-cookies-in-asp-net-website http://stackoverflow.com/questions/3737285/set-cookie-to-expire-at-end-of-session-asp-net – JSHunjan Aug 14 '14 at 08:06
  • 1
    Thats not my case, commenter. – Imad Aug 14 '14 at 08:58

3 Answers3

6

You got the right concept for deleting a cookie programmatically:

HttpCookie myCookie = new HttpCookie("IsGuest"); 
cookie.Expires = DateTime.Now.AddDays(-1d); 
Response.Cookies.Add(cookie);

However, you missed one point. The above change won't be effective until the postback completes and subsequently user initiates a new request.

MSDN says:

The next time a user makes a request to a page within the domain or path that set the cookie, the browser will determine that the cookie has expired and remove it.

So, the below code illustrates more here::

protected void DeleteCookie_ButtonClick(object sender, EventArgs e)
    {
        if (Request.Cookies["IsGuest"] != null)
        {
            HttpCookie myCookie = new HttpCookie("IsGuest"); 
            myCookie.Expires = DateTime.Now.AddDays(-1d); 
            Response.Cookies.Add(myCookie);
        }
        
        // this will always be true here as the Request i.e HttpRequest isn't 
        // modified actually as the postback isn't complete and we are accessing 
        // the Cookies collection of same request (not a new request)
        if (Request.Cookies["IsGuest"] != null)
        {
            Label1.Text = "Cookie Collection can't be modified without 
                           making a new request";
        }

    }
    
   // suppose after postback completes, 
   // user clicks a button to check the cookie, 
   // which in turn is a new request/postback/....
    protected void CheckCookie_ButtonClick(object sender, EventArgs e)
    {
        if (Request.Cookies["IsGuest"] != null)
        {
            Label1.Text = "Cookie is present!";                
        }
        else
        {
            Label1.Text = "No Cookie is present!";                
        }
    }

One last Note::

Calling the Remove method of the Cookies collection removes the cookie on the server side, so the cookie will not be sent to the client. However, the method does not remove the cookie from the client if it already exists there.

Aage
  • 5,932
  • 2
  • 32
  • 57
R.C
  • 10,417
  • 2
  • 35
  • 48
  • Can we set cookie expiration time from web config? – AuserP Sep 16 '19 at 10:00
  • @AuserP :Website wide cookie settings are applied through Web.config element . However, this element does not has any attribute to specify Timeouts for cookies Additionally, for Asp.net specific cookies such as Forms Authentication cookie, you can use element , attribute name: timeout. Same goes for Asp.net Session cookie, web.config element: In short, for (custom)cookies created in code, No setting exists in web.config for Timeouts. Do understand that user session(i.e session cookie) may expire but not necessarily the cookie created through Code – R.C Sep 16 '19 at 10:48
0

How to Expire a Cookie (on the Client)

I would not reply on ASP.NET Core to remove or expire cookies, as the server-side has very little to do with what happens on the browser. The ASP.NET application & server also has no knowledge of the names of every outdated-cookie, which paths were assigned, if some have already expired, which cookie names are no longer used from an older website, which ones were renamed, which ones are session cookies that need to remain, etc etc.

Cookies are best controlled on the client, which means running JavaScript (unfortunately).

To do that, I recommend you roll your own cookie expiration routine. Below is one I use that removes the top root-path cookies and a sub-path of cookies under the root, starting at the folder from which the script is called from. This generally means most of your cookies are removed. There are some exotic rules as to how browsers remove expired cookies under subpaths that I wont get into. In some cases some subpaths may be missed. But in general, root cookies would all be expired, and any cookies with the same scipts web path and all subpath under it, also expired.

The script below only sets expiration dates on cookies with paths matching the above rules. But the browsers are design to expire cookies under the subpath above as well. Please test in various browser, however, and customize the script as you like. This will NOT delete sessions stored as cookies!

// Get all cookies for this domain but by name-value pairs:
alert('What cookies do I have (name-value)?\r\n ' + document.cookie);

// Get all cookies
var allcookies = document.cookie;

// Splits into multiple cookies
var cookiesArray = allcookies.split(";");

// Loop through each found cookie...
if (cookiesArray && cookiesArray.length >= 0){
    for (var i = 0; i < cookiesArray.length; i++) {

        var nameString = "";
        var pathString = "";
        var expiresString = "";

        // Strip out all whitespace or formatting from the name-value pair...
        var cookieCleaned = cookiesArray[i].replace(/^\s+|\s+$/gm, '').replace(/[\t\n\r]/gm, '')

        namePair = cookiesArray[i].split("=");
        nameString = namePair[0] + "=; ";// empty the name's value

        const earlydate = new Date(0).toUTCString();
        expiresString = "expires=" + earlydate;

        // DELETE COOKIES using ROOT PATH and SUBPATH
        if (namePair[0] !== ""){

            // Reset the cookie subpath with new expiration date
            // to force the browser cache to delete it.
            var pathname = location.pathname.replace(/\/$/,'');
            if (pathname !== '') {
                pathname = "path=" + pathname + "; ";
                document.cookie = nameString + pathname + expiresString;
                alert('Final Cookie1:\r\n ' + nameString + pathname + expiresString);
            }

            // Reset the cookie rootpath, same as above.
            document.cookie = nameString + "path=/; " + expiresString;
            alert('Final Cookie2:\r\n ' + nameString + "path=/; " + expiresString);
        }
    }
}
Stokely
  • 12,444
  • 2
  • 35
  • 23
-2

Better you can remove cookie from your list

Ajay Peter
  • 153
  • 4