在内容页面之间遍历时 cookie 值消失

发布于 2024-12-06 01:43:33 字数 1285 浏览 0 评论 0原文

在我的应用程序中。有一个登录机制,它保存一个 cookie,其中包含刚刚登录我的主页加载的用户的信息

     private void CreateCookie(LoginEventArgs args)
     {
         HttpCookie cookie = new HttpCookie("user");
         cookie.Values["name"] = args.User_Name;
         cookie.Values["id"] = args.ID;
         cookie.Expires = DateTime.Now.AddDays(1);            
         Response.Cookies.Add(cookie);
     }

,我执行检查以查看此 cookie 是否存在:

   HttpCookie cookie = Request.Cookies["user"] ;
   if( (cookie != null) && (cookie.Value != ""))  
   {
        if (Session["user"] == null)
            Login_Passed(this, new LoginEventArgs(cookie.Values["name"].ToString(), int.Parse(cookie.Values["id"])));
   }

现在,如果我登录(创建 cookie),请关闭浏览器,然后运行我的应用程序。再次是饼干 存在它的值是正确的并且用户“自动”登录。

如果我首先从启动内容页面重定向到不同的内容页面 cookie 值也完好无损,

问题是当我第二次重定向回不同的内容页面时, 主页加载并进行检查 cookie 存在,但值被删除...

关于为什么会发生这种情况有什么想法吗?

顺便说一句,也许我注销的方式可能是这个问题的原因:

当我注销时,我创建了一个同名的 cookie,该 cookie 于 1 天前过期。

   private void Remove_Cookie()
   {
        HttpCookie cookie = new HttpCookie("user");
        cookie.Expires = DateTime.Now.AddDays(-1);
        Response.Cookies.Add(cookie); 
   }

在 iv'e 描述的情况下,我没有正式注销,我只是结束我的应用程序,所以这不应该 有什么影响。

in my app. there's a log in mechanism which save a cookie with the info of the user who just logged in

     private void CreateCookie(LoginEventArgs args)
     {
         HttpCookie cookie = new HttpCookie("user");
         cookie.Values["name"] = args.User_Name;
         cookie.Values["id"] = args.ID;
         cookie.Expires = DateTime.Now.AddDays(1);            
         Response.Cookies.Add(cookie);
     }

on my master page load i perform a check to see if this cookie exists or not :

   HttpCookie cookie = Request.Cookies["user"] ;
   if( (cookie != null) && (cookie.Value != ""))  
   {
        if (Session["user"] == null)
            Login_Passed(this, new LoginEventArgs(cookie.Values["name"].ToString(), int.Parse(cookie.Values["id"])));
   }

now if i Log in ( Create A cookie ) , close the browser , and run my app. again the cookie
exists it's values are correct and the user is "automatically" logged in .

if i first redirect to a different content page from the start up content page
the cookies values are also intact ,

the problem is when i redirect back to a different content page a second time,
the master page loads , makes the check
the cookie exists but the values are deleted ...

any ideas on why this happens ?

btw maybe the way i log out could be the reason for this problem :

when i log-out i create a cookie with the same name that expires 1 day ago .

   private void Remove_Cookie()
   {
        HttpCookie cookie = new HttpCookie("user");
        cookie.Expires = DateTime.Now.AddDays(-1);
        Response.Cookies.Add(cookie); 
   }

in the case iv'e described i don't log-out formally , i just end my app , so this shouldn't
have any effect .

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

太阳公公是暖光 2024-12-13 01:43:33

好吧,这个问题是不可想象的
特别感谢 Peter Bromberg

http://www.eggheadcafe.com/tutorials/aspnet/198ce250-59da-4388-89e5-fce33d725aa7/aspnet-cookies-faq.aspx

文章“消失”部分Cookie "

作者指出,如果您关注 Response.Cookies["cookie_name"]
浏览器创建一个新的空 cookie 来覆盖您的 cookie 。

我使用了这样的手表,它使我的饼干失去了它的值,当我把它从饼干上取下时,它保留了它的值。

道德是不要看 Response.Cookies[" "]
我还在其他一些帖子中读到,如果您检查

 if( Response.Cookies["cookie_name"] != null    )  

例如它也会被覆盖。

o'k , the problem was unthinkable
special thanks to Peter Bromberg

http://www.eggheadcafe.com/tutorials/aspnet/198ce250-59da-4388-89e5-fce33d725aa7/aspnet-cookies-faq.aspx

in the section of the Article " The Disappearing Cookie "

the author states that if you have a watch on Response.Cookies["cookie_name"]
the browser creates a new empty cookie that overrides your cookie .

i used such a watch which made my cookie loose it's values ,and when i took it off the cookie kept its values.

the moral is DON't WATCH Response.Cookies[" "]
also i read in some other post that if you check

 if( Response.Cookies["cookie_name"] != null    )  

for example it also gets overridden.

清晨说晚安 2024-12-13 01:43:33

为了重申并建立在已经陈述的基础上(是的,我知道这是一个 4 年前的问题),我发现最好构建一个实用程序来处理这个问题 - 主要是因为我想经常检查特定的 cookie。

这不会触及响应,而只会读取请求。

    public static HttpCookie GetCookie(string cookieName)
    {
        HttpCookie rqstCookie = HttpContext.Current.Request.Cookies.Get(cookieName);
        /*** NOTE: it will not be on the Response!
         *   this will trigger the error noted in the original question and
         *   create a new, empty cookie which overrides it
         *   
            HttpCookie respCookie = HttpContext.Current.Response.Cookies.Get(cookieName);
         * 
         */
        if (rqstCookie != null && !String.IsNullOrEmpty(rqstCookie.Value))
        {
            // is found on the Request
            return rqstCookie;
        }
        else
        {
            return null;
        }
    }

经验法则

始终从请求中读取并写入响应。

谢谢 eran!这篇文章正是我所需要的

To reiterate and build upon what has already been stated (yes, I know this is a 4 year old question) I have found it best to build a utility to handle this - mostly because I want to check that specific cookie often.

This will not touch the Response but only read from the Request.

    public static HttpCookie GetCookie(string cookieName)
    {
        HttpCookie rqstCookie = HttpContext.Current.Request.Cookies.Get(cookieName);
        /*** NOTE: it will not be on the Response!
         *   this will trigger the error noted in the original question and
         *   create a new, empty cookie which overrides it
         *   
            HttpCookie respCookie = HttpContext.Current.Response.Cookies.Get(cookieName);
         * 
         */
        if (rqstCookie != null && !String.IsNullOrEmpty(rqstCookie.Value))
        {
            // is found on the Request
            return rqstCookie;
        }
        else
        {
            return null;
        }
    }

rule-of-thumb

Always read from the Request and write to the Response.

Thanks eran! this post was exactly what I needed

伤痕我心 2024-12-13 01:43:33

尝试以下操作:

  • 如果您在本地计算机上进行开发,请将您的应用程序放在一些免费网页上,这样就不会因为您位于本地主机而受到“特殊待遇”。
  • 如果您已经在网络服务器上,并且重定向发生在两个不同的域之间,您可能需要在 google 中搜索“同源策略”或阅读以下内容:http://en.wikipedia.org/wiki/Same_origin_policy(该文档讨论了 javascript,但对于 cookie 也是如此)。

try the following:

  • If you are developing on your local machine, put your app on some free web page, so there will be no 'special treatment' because you're in the local host.
  • If you already are on a web-server, and if the re-directions are between tow different domains, you may want to search google for 'same origin policy' or read this: http://en.wikipedia.org/wiki/Same_origin_policy (the document talks about javascript, but its true also for cookies).
套路撩心 2024-12-13 01:43:33

使用以下方法从 cookie 中获取值:

public string GetValueFromCookies(HttpCookieCollection cookies)
{
    if (cookies == null)
    {
        throw new ArgumentNullException(nameof(cookies));
    }

    // check the existence of key in the list first
    if (Array.IndexOf(cookies.AllKeys, key) < 0)
    {
        return null;
    }

    // because the following line adds a cookie with empty value if it's not there
    return cookies[key].Value;
}

Use the following approach to get a value from cookies:

public string GetValueFromCookies(HttpCookieCollection cookies)
{
    if (cookies == null)
    {
        throw new ArgumentNullException(nameof(cookies));
    }

    // check the existence of key in the list first
    if (Array.IndexOf(cookies.AllKeys, key) < 0)
    {
        return null;
    }

    // because the following line adds a cookie with empty value if it's not there
    return cookies[key].Value;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文