【问题标题】:RememberMe Cookie set expirations time but on Firebug appears as Expiration as SessionRememberMe Cookie 设置过期时间,但在 Firebug 上显示为 Expiration as Session
【发布时间】:2014-04-05 10:43:11
【问题描述】:

我正在使用 C# 和 MVC5 使用以下代码创建自己的 cookie:

// Prepare the ticket
HttpContext.Response.Cookies.Clear();
FormsAuthenticationTicket ticket = 
   new FormsAuthenticationTicket(1, 
                                 "MYNAME", 
                                 DateTime.Now, 
                                 DateTime.Now.AddDays(10), // <<- Expires 10 days 
                                 true, 
                                 null);

// Encrpt the ticket
string encryptedCookie = FormsAuthentication.Encrypt(ticket);

// Create new cookie
HttpCookie cookie = new HttpCookie("MYNAME", encryptedCookie);
cookie.Path = FormsAuthentication.FormsCookiePath;

// Send the Cookie back to the browser
HttpContext.Response.Cookies.Add(cookie);

在 Web.Config 中,我将名称设置为

<authentication mode="Forms">
   <forms name="MYNAME" loginUrl="~/Account/Login"></forms>
</authentication>

但是当我查看 Firebug 时,Cookie 显示为“MYNAME”,但“expires”设置为 Session
事实上,当我关闭浏览器时,cookie 消失了,当我回到网站时,我总是需要重新登录。所有其他浏览器也是如此。

我做错了什么??

【问题讨论】:

    标签: c# asp.net-mvc cookies web-config remember-me


    【解决方案1】:

    问题是我将过期设置为“票证”级别,而不是“Cookie”级别。

    添加

    cookie.Expires = ticket.Expiration; 
    

    ..解决了问题!!

    所以整个代码应该是这样的:

    // Prepare the ticket
    HttpContext.Response.Cookies.Clear();
    FormsAuthenticationTicket ticket = 
       new FormsAuthenticationTicket(1, 
                                     "MYNAME", 
                                     DateTime.Now, 
                                     DateTime.Now.AddDays(10), // <<- Expires 10 days 
                                     true, 
                                     null);
    
    // Encrpt the ticket
    string encryptedCookie = FormsAuthentication.Encrypt(ticket);
    
    // Create new cookie
    HttpCookie cookie = new HttpCookie("MYNAME", encryptedCookie);
    cookie.Path = FormsAuthentication.FormsCookiePath;
    
    // THE MISSING LINE IS THIS ONE
    cookie.Espires = ticket.Expiration;   // <<- Uses current Ticket Expiration
    
    // Send the Cookie back to the browser
    HttpContext.Response.Cookies.Add(cookie);
    

    【讨论】:

      【解决方案2】:

      它如何与其他浏览器配合使用?铬,IE? 如果它在那里工作正常,那么它也应该在 FF 上工作。 如果它在那里不起作用,那么可能是代码有问题

      看看这些文章 FormsAuthenticationTicket expires too soon

      基本款 http://www.codeproject.com/Articles/244904/Cookies-in-ASP-NET http://msdn.microsoft.com/en-us/library/ms178194.ASPX

      谢谢

      【讨论】:

      • 他们都有同样的问题..他们都以某种方式在浏览器级别将他们的过期设置为“会话”。问题不是我的池回收,而是当我关闭浏览器时 cookie 过期。如果我不关闭它,它会保持活动状态并在我返回站点时自动登录。
      • Ok 在配置中添加超时,然后尝试。把它设置为 timeout=1200 并尝试一下
      • 不,仍然无法正常工作。我对此抱有小小的希望:-)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-17
      • 1970-01-01
      • 2017-01-11
      • 1970-01-01
      相关资源
      最近更新 更多