C# 记住我ASP.NET表单身份验证中的功能不';行不通

C# 记住我ASP.NET表单身份验证中的功能不';行不通,c#,forms-authentication,remember-me,C#,Forms Authentication,Remember Me,我正在使用ASP.NET表单身份验证将用户登录到我们正在开发的网站 该功能的一部分是“记住我”复选框,如果用户选中该复选框,该复选框将记住用户一个月 用户登录的代码如下: public static void Login(HttpResponse response, string username, bool rememberMeChecked) { FormsAuthentication.Initialize(); FormsAuthenticationTicket tkt = n

我正在使用ASP.NET表单身份验证将用户登录到我们正在开发的网站

该功能的一部分是“记住我”复选框,如果用户选中该复选框,该复选框将记住用户一个月

用户登录的代码如下:

public static void Login(HttpResponse response, string username,
  bool rememberMeChecked)
{
  FormsAuthentication.Initialize();
  FormsAuthenticationTicket tkt = new FormsAuthenticationTicket(1, username, DateTime.Now,
    DateTime.Now.AddMinutes(30), rememberMeChecked,
    FormsAuthentication.FormsCookiePath);
  HttpCookie ck = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(tkt));
  ck.Path = FormsAuthentication.FormsCookiePath;

  if (rememberMe)
    ck.Expires = DateTime.Now.AddMonths(1);

  response.Cookies.Add(ck);
}
web.config中的相关部分如下所示:

<authentication mode="Forms">
  <forms loginUrl="Home.aspx" defaultUrl="~/" slidingExpiration="true" timeout="43200" />
</authentication>

这会记录用户,但如果用户不使用该站点,则会在半小时后将其注销,尽管其持久性属性(rememberMeChecked)设置为true,如果为true,则cookie将在一个月后过期。这里有我遗漏的东西吗

提前感谢,,
在我看来,您正在检查“rememberMe”,而不是您传递的名为“rememberchecked”的变量。

请尝试在web.config中设置表单标记的属性

而且,它在调试这类问题方面非常出色


只需再次阅读代码,您就已经在票证构造函数中指定了
DateTime.Now.AddMinutes(30)
,您必须检查这是否会影响它您已经在
FormsAuthentication票证的构造函数中指定了
DateTime.Now.AddMinutes(30)
。这就是设置登录过期的原因。

您的身份验证票证似乎仍然配置为在半小时后过期,即使cookie本身在30天后过期。您可能还必须延长票据的生命周期:

public static void Login(HttpResponse response, string username,
    bool rememberMeChecked)
{
    DateTime expiration = DateTime.Now.AddMinutes(30);
    if (rememberMe) {
        expiration = DateTime.Now.AddMonths(1);
    }

    FormsAuthentication.Initialize();
    FormsAuthenticationTicket tkt = new FormsAuthenticationTicket(1, username,
        DateTime.Now, expiration, rememberMeChecked,
        FormsAuthentication.FormsCookiePath);

    HttpCookie ck = new HttpCookie(FormsAuthentication.FormsCookieName,
        FormsAuthentication.Encrypt(tkt));
    ck.Path = FormsAuthentication.FormsCookiePath;
    response.Cookies.Add(ck);
}

我意识到身份验证单必须更新,而不仅仅是阅读。我的应用程序\u BeginRequest方法现在如下所示:

 if (!Request.IsAuthenticated)
  {
    HttpCookie ck = Request.Cookies[FormsAuthentication.FormsCookieName];

    if (ck != null)
    {
      FormsAuthenticationTicket oldTicket = FormsAuthentication.Decrypt(ck.Value);
      UserManagementUtils.RenewFormsAuthenticationTicket(Response, oldTicket);
    }
  }

这似乎已经解决了问题。

我不确定这是否会对这个实例产生影响,但是,使用
表单身份验证。重定向fromloginpage(userName,memberme)
有什么错?是否需要手动创建票据?如果您在配置中指定超时,那么您不需要手工编写代码,AFAIK。另外,
rememberMe
设置在哪里?这应该由框架负责。我认为上面的答案中提到的问题是,您没有设置票据的有效期,而只是设置了cookie。
name
链接已断开。