无法设置cookie值

时间:2013-12-17 22:27:50

标签: c# asp.net

我有一个方法调用docount()

代码

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);

由于某种原因,它总是点击else语句。知道我做错了什么。

1 个答案:

答案 0 :(得分:2)

它应该是这样的:

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);
}

Request读取并写信至Response