检查Cookie是否存在 [英] Check if Cookie Exists
问题描述
从堆栈溢出快速搜索我看到人们建议以下方式检查是否存在cookie:
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
( Page
类内):
this.Response.Cookies["cookie_name"] != null
然而,当我尝试使用索引器Get方法)检索不存在的cookie,它似乎实际上创建一个'默认'cookie的名称并返回,因此无论使用什么cookie名称,它从不返回null。 (甚至更糟 - 创建一个不需要的cookie)
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)
我在这里做错了,或者有一个不同的方法来简单地检查特定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.Cookies
包含将被发回的Cookie到浏览器。如果你想知道cookie是否存在,你应该看看 Request.Cookies
。
Response.Cookies
contains the cookies that will be sent back to the browser. If you want to know whether a cookie exists, you should probably look into Request.Cookies
.
查看Cookie是否存在,您可以检查 Cookies.Get(string)
。 但是,如果您在Response对象上使用此方法,并且Cookie 不存在,则会创建该cookie。
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.
有关 HttpCookieCollection.Get
方法(字符串)
See MSDN Reference for HttpCookieCollection.Get
Method (String)
这篇关于检查Cookie是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!