Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cookie loses value in ASP.net

I have the following code that sets a cookie:

  string locale = ((DropDownList)this.LoginUser.FindControl("locale")).SelectedValue;
  HttpCookie cookie = new HttpCookie("localization",locale);
  cookie.Expires= DateTime.Now.AddYears(1);
  Response.Cookies.Set(cookie);

However, when I try to read the cookie, the Value is Null. The cookie exists. I never get past the following if check:

         if (Request.Cookies["localization"] != null && !string.IsNullOrEmpty(Request.Cookies["localization"].Value))

Help?

like image 858
Joda Avatar asked Oct 16 '08 09:10

Joda


2 Answers

The check is done after a post back? If so you should read the cookie from the Request collection instead.

The cookies are persisted to the browser by adding them to Response.Cookies and are read back from Request.Cookies.

The cookies added to Response can be read only if the page is on the same request.

like image 60
Aleris Avatar answered Sep 20 '22 15:09

Aleris


The most likely answer is seen on this post

When you try to check existence of a cookie using Response object rather than Reqest, ASP.net automatically creates a cookie.

Edit: As a note, I ended up writing software that needed to check the existence of cookies that ASP.NET makes a nightmare due to their cookie API. I ended up writing a conversion process that takes cookies from the request and makes my state object. At the end of the request I then translate my state object back to cookies and stuff them in the response (if needed). This alleviated trying to figure out if cookies are in the response, to update them instead, avoiding creating of pointless cookies etc.

like image 30
Chris Marisic Avatar answered Sep 22 '22 15:09

Chris Marisic