简体   繁体   中英

Cookie expiration issue in asp.net

I am creating a cookie and getting a textbox value in it.I need to expire it and then has to print a message by checking that it has been expired or not.I am doing as following

 HttpCookie usercookie = new HttpCookie("userinfo");
        Response.Cookies["gettingusername"].Value = textbox_username.Text;
        Response.Cookies["gettingusername"].Expires = DateTime.Now;
        Response.Cookies.Add(usercookie);
        if (Request.Cookies["gettingusername"]!=null)
        {
            Response.Write("Cookie is Not Expired");
        }
        else
        {
           Response.Write("Cookie Expired");
        }

But it always says:-

Cookie is Not Expired  

I am newbie for it.Please help. Thanks in advance.

You can do it like below:

myCookie.Expires = DateTime.Now.AddDays(-1);

if(myCookie.Expires > DateTime.Now)
  Response.Write("Cookie not Expired");
else
  Response.Write("Cookie Expired");

Browser is responsible for removing expired cookies. You just need to set time in the future that it will expire. For example :

if (Request.Cookies["gettingusername"] != null)
{
    Response.Write("Cookie is not expired")
    Response.Write("Value exists : " + Request.Cookies["gettingusername"]);
}
else
{
   Response.Write("Cookie is expired, creating a new cookie.");
   Response.Cookies.Add(new HttpCookie("gettingusername")
   {
       Value = textbox_username.Text,
       Expires = DateTime.Now.AddDays(1)
   });
}

Try the following...

if (Request.Cookies["gettingusername"] != null)
{
    HttpCookie myCookie = new HttpCookie("userinfo");
    myCookie.Expires = DateTime.Now.AddDays(-1);//add -1 days
    Response.Cookies.Add(myCookie);
}

Can't understand exactly what are you trying to achieve by that. You should set them and check if they are expired in different methods.

For example, you can set cookie when press 'Set cookie' button and expire them in action 'Expire Cookie'

这是您现在可以删除cookie的方法..!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM