Asp.Net -如何过期Cookie



尝试

 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;

并尝试注释未注释的代码和取消注释已注释的代码,但是

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

始终运行,Request.Cookies["IsGuest"]不为null

您获得了以编程方式删除cookie的正确概念:

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

但是,你漏掉了一点。 The above change won't be effective until the postback completes and subsequently user initiates a new request .

MSDN 说:

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.

下面的代码说明了更多::

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!";                
        }
    }

最后说明::

调用cookie集合的Remove方法将删除服务器端的cookie,因此cookie不会被发送到客户端。但是,如果该cookie已经存在,则该方法不会从客户端删除该cookie。

如何使Cookie过期(在客户端)

我不会回复ASP。. NET Core删除或过期cookie ,因为服务器端与浏览器上发生的事情几乎没有关系。ASP。. NET应用程序服务器也不知道每个过期cookie的名称,哪些路径被分配,如果有些已经过期,哪些cookie名称不再用于旧网站,哪些已被重命名,哪些是会话cookie需要保留,等等。

cookie最好在客户端上控制,这意味着运行JavaScript(不幸的是)。

要做到这一点,我建议您滚动自己的cookie过期例程。下面是我使用的一种方法,它删除了顶部根路径cookie和根路径下的cookie子路径,从调用脚本的文件夹开始。这通常意味着您的大部分cookie将被删除。关于浏览器如何在子路径下删除过期的cookie,有一些奇特的规则,我不会进入。在某些情况下,可能会遗漏一些子路径。但一般来说,根cookie都会过期,任何具有相同脚本web路径及其所有子路径的cookie也会过期。

下面的脚本只在路径匹配上述规则的cookie上设置过期日期。但是浏览器的设计也会使上述子路径下的cookie过期。但是,请在各种浏览器中进行测试,并根据自己的喜好自定义脚本。这不会删除会话存储为cookie !

// Get all cookies for this domain but by name-value pairs:
alert('What cookies do I have (name-value)?rn ' + 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(/[tnr]/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:rn ' + nameString + pathname + expiresString);
            }
            // Reset the cookie rootpath, same as above.
            document.cookie = nameString + "path=/; " + expiresString;
            alert('Final Cookie2:rn ' + nameString + "path=/; " + expiresString);
        }
    }
}

最好将cookie从列表中删除

最新更新