简体   繁体   中英

Not able to set cookie value

i have a method call docount()

the code

if (Request.Cookies["searchCounter"] != null)
{
    Response.Write("cookie old cookie ");
    int scvalue = int.Parse(Request.Cookies["searchCounter"].Value);
    int sc =  scvalue + 1;
    Request.Cookies["searchCounter"].Value = sc.ToString();
    Request.Cookies["searchCounter"].Expires = DateTime.Now.AddDays(2);

}
else
{
    Response.Write("new cookie ");
    Response.Cookies["searchCounter"].Value = "1";
    Response.Cookies["searchCounter"].Expires = DateTime.Now.AddDays(2);
}


Response.Write("Cookie value: " + Request.Cookies["searchCounter"].Value);

for some reason it is always hitting the else statement. any idea what i did wrong.

It should be something like this:

if (Request.Cookies["searchCounter"] != null && Request.Cookies["searchCounter"].Value != "")
{
    // some code...
    Response.Cookies["searchCounter"].Value = "some data";
    Response.Cookies["searchCounter"].Expires = DateTime.Now.AddDays(1);
}
else
{
    Response.Cookies["searchCounter"].Value = "some data";
    Response.Cookies["searchCounter"].Expires = DateTime.Now.AddDays(1);
}

Read from Request and write to Response .

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