检查 Cookie 是否存在 [英] Check if Cookie Exists

查看:41
本文介绍了检查 Cookie 是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过对 Stack Overflow 的快速搜索,我看到有人建议使用以下方法来检查 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

但是,当我尝试使用索引器(或 Cookies.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 的信息,请参阅 MSDN 参考.Get 方法(字符串)

See MSDN Reference for HttpCookieCollection.Get Method (String)

这篇关于检查 Cookie 是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆