登录表单中的“记住我”功能

时间:2013-12-15 09:16:13

标签: c# checkbox remember-me

我正在使用linq进行实体连接。我希望用户在登录帐户后保持登录状态,这是我的代码。它不起作用。请帮助

    if (this.ChkRememberme != null && this.ChkRememberme.Checked == true)
    {
        HttpCookie cookie = new HttpCookie(TxtUserName.Text, TxtPassword.Text);
        cookie.Expires.AddYears(1);
        Response.Cookies.Add(cookie);
    }

2 个答案:

答案 0 :(得分:3)

 if (this.ChkRememberme != null && this.ChkRememberme.Checked == true)
 {
    int timeout = rememberMe ? 525600 : 30; // Timeout in minutes, 525600 = 365 days.
    var ticket = new FormsAuthenticationTicket(TxtUserName.Text, TxtPassword.Text);
    string encrypted = FormsAuthentication.Encrypt(ticket);
    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
    cookie.Expires = System.DateTime.Now.AddMinutes(timeout);// Not my line
    cookie.HttpOnly = true; // cookie not available in javascript.
    Response.Cookies.Add(cookie);
}

转到web.config并找到身份验证元素。您可以在那里设置Cookie到期时间(以分钟为单位),例如:

<system.web>
    <authentication mode="Forms">
        <forms loginUrl="~/Account/Login" 
               name="myCookie"                  <!-- optional, if you want to rename it -->
               timeout="2880" />                <!-- expires in 48 hours -->
    </authentication>
</system.web>

来源:how to apply "Remember Me" in c#

希望这有帮助

快乐编码.. !!

答案 1 :(得分:0)

我建议您在应用中使用MembershipReboot进行身份验证(包含示例)。