Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net cookie not saved

Can you please tell me what am I doing wrong here. Why the Cookie data is not stored when I reload the page:

protected void Page_Load(object sender, EventArgs e)
{
   if (!IsPostBack)
   {
      // it is always null !!!!               
      if (Response.Cookies["user_id"].Value != null) 
      {
          //code never gets here
      }
   }
}

and this is the code for storing the cookie (after clicking a checkbox):

protected void CheckBoxRememberMe_Click(object sender, EventArgs e)
{
    Response.Cookies["user_id"].Value = tbUserID.Text;
    Response.Cookies["user_id"].Expires = DateTime.Now.AddDays(15);
}

So: I click on the checkbox, the value of tbUserID textbox is stored in the HttpCookie, then I reload the page (refresh) and the value is null.

Any idea ?

like image 636
Ranch Avatar asked Feb 22 '23 14:02

Ranch


1 Answers

When checking for the cookie you want to be making a request rather than adding the cookie to the response.

   if (Request.Cookies["user_id"].Value != null) 
   {
       //code should get here
   }
like image 114
Fishcake Avatar answered Feb 25 '23 05:02

Fishcake