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?
document. cookie. indexOf('cookie_name='); It will return -1 if that cookie does not exist.
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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With