在我的一个程序里使用了Forms身份验证,在验证通过后,我手动设置Cookie的过期时间为1年后,但是经过实验,发现这个设置未起作用,第二天还是需要重新登录在登录前,我还特意进入Cookie保存的目录:c:\Documents and Settings\Administrator\Local Settings\Temporary Internet Files
查看那个Cookies文件,过期时间也确实是2011年,如图(这个图是我刚刚再次登录的,所以时间是今天):
贴出我的源代码:
string uName = Login1.UserName;
if (FormsAuthentication.Authenticate(uName, Login1.Password))
{
    bool remember = Login1.RememberMeSet;
    //FormsAuthentication.SetAuthCookie(uName, remember);
    if (!remember)
        FormsAuthentication.RedirectFromLoginPage(uName, false);
    else
    {
        // 使用下面的语句,只能记住30分钟左右
        //FormsAuthentication.RedirectFromLoginPage(uName, true);        HttpCookie cookie = FormsAuthentication.GetAuthCookie(uName, true);
        cookie.Expires = DateTime.Now.AddYears(1);  // 记住我时,设置1年有效
        Response.Cookies.Add(cookie);
        Response.Redirect(FormsAuthentication.GetRedirectUrl(Login1.UserName, true));
    }
}

解决方案 »

  1.   

    为什么我设置验证Cookie过期为1年后,而实际的有效时间还是30分钟呢?我通过HttpWatch抓取,发现这个AspxAuth的Cookie也正常提交了我估计是不是这个Cookie的值,是加入了时间信息在内的查询MSDN,没发现可以设计Cookie可以长期有效的设定我现在是自己去设置cookie,不使用Forms的这个cookie,来判断是否要记住登录
      

  2.   

    你可以输出cookie值看一下,看有没有值出来,我估计可能是代码逻辑上有点问题了吧,我用的都可以啊
      

  3.   

    http://topic.csdn.net/u/20080218/09/c7a5af3c-00bc-4d76-aab1-8b2570382778.html
      

  4.   

    本帖最后由 net_lover 于 2010-09-01 11:02:43 编辑
      

  5.   

    是说这个TimeOut吗?
    <forms loginUrl="Admin/Login.aspx" timeout="xxx">
      

  6.   

    通过http://referencesource.microsoft.com/下载到的源代码,查看了一下FormsAuthentication.GetAuthCookie方法,在该方法里,是这样创建票据的:// 从Forms的TimeOut获取Cookie超时时间
    _Timeout = (int) settings.Forms.Timeout.TotalMinutes;private static HttpCookie GetAuthCookie(String userName, bool createPersistentCookie, String strCookiePath, bool hexEncodedTicket) {
    ....
     FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
            2, // version 
            userName, // User-Name 
            DateTime.Now, // Issue-Date
            DateTime.Now.AddMinutes(_Timeout), // Expiration 
            createPersistentCookie, // IsPersistent
            String.Empty, // User-Data
            strCookiePath // Cookie Path
            ); 所以看来,我的要求有2个解决方案:
    1、设置Web.config里的Forms的TimeOut;
    2、自己创建票据最后修正代码为:
    DateTime now = DateTime.Now;
    DateTime end = now.AddYears(1);// 设置1年后过期
    //建立身份验证票对象  
    FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket(1, uName, now, end, true, string.Empty);
    string HashTicket = FormsAuthentication.Encrypt(Ticket); //加密序列化验证票为字符串  
    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, HashTicket) { Expires = end };//生成Cookie  
    Response.Cookies.Add(cookie);// FormsAuthentication.SetAuthCookie();
    Response.Redirect(FormsAuthentication.GetRedirectUrl(Login1.UserName, true));
      

  7.   

    感谢3楼 silentwins 给的提示