2012-11-28 54 views
1

我有一个使用FormsAuthentication的登录系统,出于某种原因,在关闭和打开浏览器时将我注销。以下是我如何设置我的登录代码:关闭浏览器后登录状态丢失

  FormsAuthenticationTicket ticket; 

       ticket = new FormsAuthenticationTicket(1, tbUsername.Text, DateTime.Now, DateTime.Now.AddYears(1), true, string.Empty, FormsAuthentication.FormsCookiePath); 

      string encryptedTicket = FormsAuthentication.Encrypt(ticket); 

      HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); 
      cookie.HttpOnly = true; 

      //Add the cookie to the request 
      Context.Response.Cookies.Add(cookie); 

正如您所看到的,我已将cookie设置为在会话中持续存在。这是我的web.config部分:

<authentication mode="Forms"> 
    <forms slidingExpiration="false" loginUrl="~/Login.aspx" name="BOIGAUTH" defaultUrl="~/Admin/Settings.aspx"/> 
</authentication> 

此外,SessionState在此特定应用程序上被禁用。任何人都知道什么是错的?

顺便说一句,离开应用程序浏览器超过2小时,让我登录,即使我没有与网站互动。关闭浏览器时,Cookie只会丢失。

+1

您正在使用哪种浏览器? – curtisk

+0

我在Firefox和Chrome上对它进行了测试,我不认为这是浏览器问题。 – TheGateKeeper

回答

5

如果您没有在cookie上设置过期时间,它将仅为浏览器会话专用cookie并在您关闭所有浏览器实例后消失。

您需要在Cookie上设置一些过期时间,以便与Expires属性保持一致。

HttpCookie cookie = new HttpCookie(
    FormsAuthentication.FormsCookieName, encryptedTicket); 
cookie.HttpOnly = true; 
cookie.Expires = DateTime.Now.AddMinutes(1000); 

附注:确保您的浏览器未配置为关闭所有cookie。

+0

我已经把时间放在了代码中,这样还不够吗? – TheGateKeeper

+0

@TheGateKeeper,不知道“Ticker”是什么......您需要cookie本身设置过期时间,浏览器不关心cookie的价值。 –

+1

我的意思是Ticket,对不起。它有一个到期值,所以我认为它是cookie过期。将尝试将其设置在Cookie和Ticket上。 – TheGateKeeper