C# 检查 Cookie 是否存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13058574/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:30:43  来源:igfitidea点击:

Check if Cookie Exists

c#asp.netcookieswebformsasp.net-4.0

提问by Acidic

From a quick search on Stack OverflowI 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 Pageclass):

或(在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 createa '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)

但是,当我尝试使用索引器(或 Cookies.Get 方法)检索不存在的 cookie 时,它​​似乎实际上创建了一个具有该名称的“默认”cookie 并返回该名称,因此无论我使用什么 cookie 名称它永远不会返回 null。(更糟糕的是 - 创建一个不需要的 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 的存在?

采纳答案by zmbq

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 into Request.Cookies.

Response.Cookies包含将发送回浏览器的 cookie。如果您想知道 cookie 是否存在,您可能应该查看Request.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'texist, then that cookie will be created.

无论如何,要查看 cookie 是否存在,您可以检查Cookies.Get(string). 但是,如果您在 Response 对象上使用此方法并且 cookie存在,则将创建该 cookie。

See MSDN Reference for HttpCookieCollection.GetMethod (String)

有关方法(字符串),请参阅 MSDN 参考HttpCookieCollection.Get

回答by Alexei Levenkov

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. But incoming cookies are never reflected in Response.

旁注:cookie 被复制到 Request on Response.Cookies.Add,这会检查它们中的任何一个是否对新添加的 cookie 表现相同。但是传入的 cookie 永远不会反映在Response.

This behavior is documented in HttpResponse.Cookiesproperty:

此行为记录在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 集合中可用,即使响应尚未发送到客户端。

回答by marisks

Sometimes you still need to know if Cookie exists in Response. Then you can check if cookie key exists:

有时你仍然需要知道 Cookie 是否存在于 Response 中。然后你可以检查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. If Cookie doesn't exist I don't touch it:

就我而言,我必须在 Global.asax 中的 Application_EndRequest 方法中修改响应 Cookie。如果 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
}

回答by Fiddles

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(string),这不会修改 cookie 集合。

is maybe not fully correct, as Cookies.Get(string) will actually create a cookie with that name, if it does not already exist. However, as he said, you need to be looking at Request.Cookies, not Response.Cookies So, something like:

可能不完全正确,因为 Cookies.Get(string) 实际上会创建一个具有该名称的 cookie,如果它不存在的话。但是,正如他所说,您需要查看 Request.Cookies,而不是 Response.Cookies 因此,类似于:

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

回答by Levitikon

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")

回答by Hernan Bogantes

You can do something like this to find out the cookies's value:

您可以执行以下操作来找出 cookie 的值:

Request.Cookies[SESSION_COOKIE_NAME].Value

回答by Trevor

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 Requestand Responseobjects contain Cookiesproperties, which are HttpCookieCollectionobjects.

无论是RequestResponse对象包含Cookies的属性,它们是HttpCookieCollection对象。

Request.Cookies:

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 nullvalue.
  • 此集合包含从客户端收到的 cookie
  • 此集合是只读的
  • 如果您尝试访问此集合中不存在的 cookie,您将收到一个null值。

Response.Cookies:

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 NOTexist in the Request.Cookiescollection, it will be added (but if the Request.Cookiesobject 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.Cookiescollection.
  • 此集合仅包含服务器在当前请求期间添加的 cookie。
  • 这个集合是可写的
  • 如果您尝试访问此集合中不存在的 cookie,您将收到一个新的 cookie 对象;如果您尝试访问的 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")
  • 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 requestby one of these methods...

正在尝试通过以下方法之一检查服务器在当前请求期间添加的 cookie ...

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

...will result in the creation of a cookie in the Response.Cookiescollection and the state will evaluate to true.

...将导致在Response.Cookies集合中创建一个 cookie,状态将评估为true