Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Cookie Exists

From a quick search on Stack Overflow I saw people suggesting the following way of checking if a cookie exists:

HttpContext.Current.Response.Cookies["cookie_name"] != null 

or (inside a Page class):

this.Response.Cookies["cookie_name"] != null 

However, when I try to use the indexer (or the Cookies.Get method) to retrieve a cookie that does not exist it seems to actually create a 'default' cookie with that name and return that, thus no matter what cookie name I use it never returns null. (and even worse - creates an unwanted cookie)

Am I doing something wrong here, or is there a different way of simply checking for the existance of a specific cookie by name?

like image 414
Acidic Avatar asked Oct 24 '12 22:10

Acidic


People also ask

How do I know if my cookies exist?

document. cookie. indexOf('cookie_name='); It will return -1 if that cookie does not exist.

How do I know if my cookies are expired?

Right-click anywhere on a web page, on the website where you want to check the cookie expiration date. Then, open up the developer tools by selecting Inspect or Inspect element, depending on the browser.


1 Answers

Sometimes you still need to know if Cookie exists in Response. Then you can check if cookie key exists:

HttpContext.Current.Response.Cookies.AllKeys.Contains("myCookie") 

More info can be found here.

In my case I had to modify Response Cookie in Application_EndRequest method in Global.asax. If Cookie doesn't exist I don't touch it:

string name = "myCookie"; HttpContext context = ((HttpApplication)sender).Context; HttpCookie cookie = null;  if (context.Response.Cookies.AllKeys.Contains(name)) {     cookie = context.Response.Cookies[name]; }  if (cookie != null) {     // update response cookie } 
like image 63
marisks Avatar answered Oct 07 '22 22:10

marisks