如何使用在自定义会员资格中记住我

时间:2013-10-18 06:33:00

标签: c# asp.net web-applications web-config membership-provider

我在web apllication 4中使用自定义成员资格提供程序,并在web.config中使用此代码:

<httpCookies httpOnlyCookies="true" />
<authentication mode="Forms">
  <forms loginUrl="~/Login.aspx" timeout="2880" />
</authentication>

会员资格和登录工作正常,但请记住我没有工作。

修改

并将此代码用于登录用户:

public static void SetupFormsAuthTicket(string userName, bool persistanceFlag)
    {
        using (EntitiesConnection EF = new EntitiesConnection())
        {
            var obj = (from m in EF.Memberships.ToList()
                       where m.Username == userName
                       select m).FirstOrDefault();

            var userId = obj.UserId;
            var userData = userId.ToString(CultureInfo.InvariantCulture);
            var authTicket = new FormsAuthenticationTicket(1, //version
                                userName, // user name
                                DateTime.Now,             //creation
                                DateTime.Now.AddMinutes(30), //Expiration
                                persistanceFlag, //Persistent
                                userData);

            var encTicket = FormsAuthentication.Encrypt(authTicket);

            var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);

            if (authTicket.IsPersistent)
            {
                cookie.Expires = authTicket.Expiration;
            }

            HttpContext.Current.Response.Cookies.Add(cookie);
        }
    }

2 个答案:

答案 0 :(得分:0)

尝试使用cookieless="UseCookies"

<authentication mode="Forms">
  <forms loginUrl="~/Login.aspx" timeout="2880" cookieless="UseCookies"/>
</authentication>

[<强>更新

您应该在用户登录时创建持久性cookie,例如

public class LoginModel
{
    public string UserName { get; set; }
    public string Password { get; set; }
    public bool RememberMe { get; set; }
}

并在您的登录操作中:

if(ValidateUser(loginModel))
{
    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
}

答案 1 :(得分:0)

  

您似乎正在使用表单身份验证。如果是这样,请参考..   Remember me checkbox does not work with Forms Authentication

以下行将设置

 FormsAuthentication.RedirectFromLoginPage("UserName",true);

如果第二个parm为真,请记住我已激活,否则请记住我未激活

并使用此online tool创建一个机器密钥,并将其添加到您的web.config。