9

I was trying to determine if a cookie existed and if it had expired with this code:

if(HttpContext.Current.Response.Cookies["CookieName"]){
    Do stuff;
}

However after long hours of tears and sweat I noticed that this line was actually creating a blank cookie or overwriting the existing cookie and its value to be blank and expire at 0.

I solved this by doing reading ALL the cookies and looking for a match like that instead

if (context.Response.Cookies.AllKeys.Contains("CookieName"))
        {
            Do stuff;
        }

This doesn't seem optimal, and I find it weird that my initial attempt created a cookie. Does anyone have a good explanation to cookie?

jenson-button-event
  • 18,101
  • 11
  • 89
  • 155
Camathon
  • 514
  • 2
  • 5
  • 22

1 Answers1

18

You are using Response.Cookies. That's wrong - they are the cookies that are sent BACK to the browser.

To read existing cookies, you need to look at Request.Cookies:

if (context.Request.Cookies["CookieName"] != null)
{
   //Do stuff;
}
Maria Ines Parnisari
  • 16,584
  • 9
  • 85
  • 130
jenson-button-event
  • 18,101
  • 11
  • 89
  • 155
  • We had a function that created a cookie after clicking a button. Then we wanted to check for existance of that cookie during Page_PreRender. By then the cookie is not in the request yet, since we haven't sent a response out with the new cookie. Therefore we created a property that looked for the cookie first in the Response, and then if there was nothing there, in the Request. – Camathon Aug 30 '13 at 11:57
  • 2
    What was really confusing was that the first if-block I was using was always returning a cookie (sometimes empty, since trying to get a non-existing cookie from the Response will create it automatically). – Camathon Aug 30 '13 at 12:03