gpt4 book ai didi

c# - 检查 Cookie 是否存在

转载 作者:IT王子 更新时间:2023-10-29 03:53:26 25 4
gpt4 key购买 nike

通过对 Stack Overflow 的快速搜索,我看到有人建议使用以下方法检查 cookie 是否存在:

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

或(在 Page 类中):

this.Response.Cookies["cookie_name"] != null

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

我是不是做错了什么,还是有其他方法可以简单地按名称检查特定 cookie 是否存在?

最佳答案

有时候你还是需要知道Response中是否存在Cookie。然后你可以检查 cookie key 是否存在:

HttpContext.Current.Response.Cookies.AllKeys.Contains("myCookie")

可以找到更多信息 here .

在我的例子中,我必须在 Global.asax 的 Application_EndRequest 方法中修改 Response 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
}

关于c# - 检查 Cookie 是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13058574/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com