C# 如何最好地检查cookie是否存在?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18529668/
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
How to best check if a cookie exists?
提问by Cammy
I was trying to determine if a cookie existed and if it had expired with this code:
我试图确定一个 cookie 是否存在以及它是否已使用此代码过期:
if(HttpContext.Current.Response.Cookies["CookieName"]){
Do stuff;
}
However after long hours of tears and sweat I noticed that this line was actually creating a blank cookie or overwriting the existing cookie and its value to be blank and expire at 0.
然而,经过长时间的流泪和汗水,我注意到这一行实际上是在创建一个空白的 cookie 或覆盖现有的 cookie 及其值为空并在 0 时过期。
I solved this by doing reading ALL the cookies and looking for a match like that instead
我通过阅读所有饼干并寻找这样的匹配来解决这个问题
if (context.Response.Cookies.AllKeys.Contains("CookieName"))
{
Do stuff;
}
This doesn't seem optimal, and I find it weird that my initial attempt created a cookie. Does anyone have a good explanation to cookie?
这似乎不是最佳选择,我发现我最初的尝试创建了一个 cookie 很奇怪。有人对cookie有很好的解释吗?
回答by jenson-button-event
You are using Response.Cookies
. That's wrong - they are the cookies that are sent BACK to the browser.
您正在使用Response.Cookies
. 这是错误的 - 它们是发送回浏览器的 cookie。
To read existing cookies, you need to look at Request.Cookies
:
要读取现有的 cookie,您需要查看Request.Cookies
:
if (context.Request.Cookies["CookieName"] != null)
{
//Do stuff;
}