2013-02-17 115 views
6

我正在使用ASP.NET MVC,并希望能够在他们返回站点时自动登录某人(与本网站完全相同)。在asp.net mvc中设置Session的持久性cookie过期?

当我用户第一寄存器或日志设置cookie如下:

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
    1, 
    "playerid", 
    DateTime.Now, 
    DateTime.Now.AddMinutes(1), //This will be set to a longer period in live... 
    true, 
    Username + "|" + item.PlayerID.ToString(), 
    FormsAuthentication.FormsCookiePath); 

string encTicket = FormsAuthentication.Encrypt(ticket); 
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)); 

如果我通过作为用户登录测试这一点,然后看看Cookies标签在Firebug然后期满被设置到Session。如果关闭浏览器然后返回到我的网站,我将不再登录。这是我期望的,因为会话在浏览器关闭时结束(但这不是我想要发生的事情!)。

但是,如果我登录并浏览了该网站,则过了一分钟后,过期不再显示为Session,而是显示为实际日期戳记。如果我然后关闭浏览器并返回到我的网站,我自动登录。

总之,我的过期似乎设置为Session,直到我规定的实际过期日期通过(t + 1分钟这种情况下),我一直在网站上活跃(我正在使用滑动到期)。

任何想法如何让我的过期设置为我在FormsAuthentication凭单中声明的​​内容(并且不显示为Session)?

回答

9

你应该创建一个通过设置Expires属性存储在客户端硬盘一个persistent cookie

var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket) 
{ 
    // setting the Expires property to the same value in the future 
    // as the forms authentication ticket validity 
    Expires = ticket.Expiration 
}; 
Response.Cookies.Add(cookie); 

确保您指定的cookie和窗体身份验证票证相同的到期超时。现在,当你使用Firebug看,你会看到,当cookie被发射的Expires属性在将来被设置,这将使该Cookie持续性和生存的浏览器重新启动:

Set-Cookie: ASPXAUTH=...; Expires=Tue, 15-Jan-2014 21:47:38 GMT; Path=/; HttpOnly 
+0

哇!这是完美的。我喜欢这个网站!感谢Darin – 2013-02-17 14:36:45

+0

为了帮助理解cookie和票证之间的区别,这值得快速浏览http://support.microsoft.com/kb/910443?wa=wsignin1.0 – 2013-02-17 14:55:41

+0

感谢您的链接。这有助于我更好地理解它。 – 2013-02-17 16:42:29