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?
Response.Cookiescontains the cookies that will be sent back to the browser. If you want to know whether a cookie exists, you should probably look intoRequest.Cookies.Anyway, to see if a cookie exists, you can check
Cookies.Get(string). However, if you use this method on the Response object and the cookie doesn’t exist, then that cookie will be created.See MSDN Reference for
HttpCookieCollection.GetMethod (String)