简体   繁体   English

检查Cookie是否存在

[英]Check if Cookie Exists

From a quick search on Stack Overflow I saw people suggesting the following way of checking if a cookie exists: 通过快速搜索Stack Overflow,我看到人们建议使用以下方法检查cookie是否存在:

HttpContext.Current.Response.Cookies["cookie_name"] != null

or (inside a Page class): 或(在Page类中):

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. 但是,当我尝试使用索引器(或Cookies.Get方法)来检索不存在的cookie时,似乎实际上创建了一个具有该名称的“默认”cookie并返回该cookie,因此无论我使用什么cookie名称它永远不会返回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? 我在这里做错了什么,或者是否有一种不同的方式来简单地通过名称检查特定cookie的存在?

Sometimes you still need to know if Cookie exists in Response. 有时您仍然需要知道Cookie是否存在于Response中。 Then you can check if cookie key exists: 然后你可以检查cookie密钥是否存在:

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. 在我的情况下,我不得不在Global.asax中的Application_EndRequest方法中修改Response Cookie。 If Cookie doesn't exist I don't touch it: 如果Cookie不存在,我不碰它:

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
}

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. RequestResponse对象都包含Cookies属性,它们是HttpCookieCollection对象。

Request.Cookies:

  • This collection contains cookies received from the client 此集合包含从客户端收到的cookie
  • This collection is read-only 此集合是只读的
  • If you attempt to access a non-existent cookie from this collection, you will receive a null value. 如果您尝试从此集合中访问不存在的cookie,您将收到null值。

Response.Cookies:

  • This collection contains only cookies that have been added by the server during the current request. 此集合仅包含服务器在当前请求期间添加的cookie。
  • This collection is writeable 这个集合是可写的
  • If you attempt to access a non-existent cookie from this collection, you will receive a new cookie object; 如果您尝试从此集合中访问不存在的cookie,您将收到一个新的cookie对象; 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. 如果您尝试访问的cookie在Request.Cookies集合中存在,它将被添加(但如果Request.Cookies对象已经包含具有相同键的cookie,即使它的值是陈旧的,它也不会更新以反映Response.Cookies集合中新创建的cookie的更改。

Solutions 解决方案


If you want to check for the existence of a cookie from the client, do one of the following 如果要从客户端检查是否存在cookie,请执行以下操作之一

  • 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: 如果要检查服务器在当前请求期间是否存在cookie, 执行以下操作:

  • Response.Cookies.AllKeys.Contains("COOKIE_KEY") (see here ) Response.Cookies.AllKeys.Contains("COOKIE_KEY") (见这里

Attempting to check for a cookie that has been added by the server during the current request by one of these methods... 尝试通过以下方法之一检查服务器在当前请求期间添加的cookie ...

  • Response.Cookies["COOKIE_KEY"] != null
  • Response.Cookies.Get("COOKIE_KEY") != null (see here ) Response.Cookies.Get("COOKIE_KEY") != null (见这里

...will result in the creation of a cookie in the Response.Cookies collection and the state will evaluate to true . ...将导致在Response.Cookies集合中创建cookie,并且状态将评估为true

You need to use HttpContext.Current.Request.Cookies , not Response.Cookies . 您需要使用HttpContext.Current.Request.Cookies ,而不是Response.Cookies

Side note: cookies are copied to Request on Response.Cookies.Add , which makes check on either of them to behave the same for newly added cookies. 附注:将Cookie复制到Response.Cookies.Add上的Request,这会检查其中任何一个对新添加的Cookie的行为相同。 But incoming cookies are never reflected in Response . 但传入的cookie永远不会反映在Response

This behavior is documented in HttpResponse.Cookies property: HttpResponse.Cookies属性中记录了此行为:

After you add a cookie by using the HttpResponse.Cookies collection, the cookie is immediately available in the HttpRequest.Cookies collection, even if the response has not been sent to the client. 使用HttpResponse.Cookies集合添加cookie后,即使响应尚未发送到客户端,cookie也会立即在HttpRequest.Cookies集合中提供。

Response.Cookies contains the cookies that will be sent back to the browser. Response.Cookies包含将发送回浏览器的cookie。 If you want to know whether a cookie exists, you should probably look into Request.Cookies . 如果您想知道cookie是否存在,您应该查看Request.Cookies

Anyway, to see if a cookie exists, you can check Cookies.Get(string) . 无论如何,要查看cookie是否存在,您可以检查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. 但是,如果在Response对象上使用此方法并且cookie 存在,则将创建该cookie。

See MSDN Reference for HttpCookieCollection.Get Method (String) 有关HttpCookieCollection.Get方法(字符串),请参阅MSDN参考

public static class CookieHelper
{
    /// <summary>
    /// Checks whether a cookie exists.
    /// </summary>
    /// <param name="cookieCollection">A CookieCollection, such as Response.Cookies.</param>
    /// <param name="name">The cookie name to delete.</param>
    /// <returns>A bool indicating whether a cookie exists.</returns>
    public static bool Exists(this HttpCookieCollection cookieCollection, string name)
    {
        if (cookieCollection == null)
        {
            throw new ArgumentNullException("cookieCollection");
        }

        return cookieCollection[name] != null;
    }
}

Usage: 用法:

Request.Cookies.Exists("MyCookie")

Sorry, not enough rep to add a comment, but from zmbq's answer: 对不起,没有足够的代表添加评论,但是从zmbq的答案:

Anyway, to see if a cookie exists, you can check Cookies.Get(string), this will not modify the cookie collection. 无论如何,要查看cookie是否存在,您可以检查Cookies.Get(字符串),这不会修改cookie集合。

is maybe not fully correct, as Cookies.Get(string) will actually create a cookie with that name, if it does not already exist. 可能不完全正确,因为Cookies.Get(字符串)实际上会创建一个具有该名称的cookie,如果它还不存在的话。 However, as he said, you need to be looking at Request.Cookies, not Response.Cookies So, something like: 但是,正如他所说,你需要看看Request.Cookies,而不是Response.Cookies那样的东西,比如:

bool cookieExists = HttpContext.Current.Request.Cookies["cookie_name"] != null;

你可以做这样的事情来找出cookies的价值:

Request.Cookies[SESSION_COOKIE_NAME].Value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM