There are a lot of right answers here depending on what you are trying to accomplish; here's my attempt at providing a comprehensive answer:
Both the Request
and Response
objects contain Cookies
properties, which are HttpCookieCollection
objects.
Request.Cookies:
- This collection contains cookies received from the client
- This collection is read-only
- If you attempt to access a non-existent cookie from this collection, you will receive a
null
value.
Response.Cookies:
- This collection contains only cookies that have been added by the server during the current request.
- This collection is writeable
- If you attempt to access a non-existent cookie from this collection, you will receive a new cookie object; If the cookie that you attempted to access DOES NOT exist in the
Request.Cookies
collection, it will be added (but if the Request.Cookies
object already contains a cookie with the same key, and even if it's value is stale, it will not be updated to reflect the changes from the newly-created cookie in the Response.Cookies
collection.
Solutions
If you want to check for the existence of a cookie from the client, do one of the following
Request.Cookies["COOKIE_KEY"] != null
Request.Cookies.Get("COOKIE_KEY") != null
Request.Cookies.AllKeys.Contains("COOKIE_KEY")
If you want to check for the existence of a cookie that has been added by the server during the current request, do the following:
Response.Cookies.AllKeys.Contains("COOKIE_KEY")
(see here)
Attempting to check for a cookie that has been added by the server during the current request by one of these methods...
Response.Cookies["COOKIE_KEY"] != null
Response.Cookies.Get("COOKIE_KEY") != null
(see here)
...will result in the creation of a cookie in the Response.Cookies
collection and the state will evaluate to true
.
Request
instead ofResponse seems
to work the way I want it to. Thanks (both answers are pretty much the same, but you answered first) – Rempe