Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to best check if a cookie exists? [duplicate]

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?

like image 653
Cammy Avatar asked Aug 30 '13 09:08

Cammy


1 Answers

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;
}
like image 114
jenson-button-event Avatar answered Sep 18 '22 20:09

jenson-button-event