更新自定义会员用户

Update custom membershipuser

我似乎无法在任何地方找到这个问题的答案。我在自己的表中使用自定义会员提供者和会员用户,这似乎比它的价值要麻烦得多。更新用户记录时,我似乎也需要更新它的会员用户实例,否则在我依赖会员用户的数据时,它与更新后的数据库不对应。

我创建了自己的更新会员用户方法,因为现有方法只接受它自己的 MembershipUser class:

public static void UpdateAccountUser(AccountUser accountUser)
    {
        // Custom MembershipUser
        ToMembershipUser user = new ToMembershipUser(
                    "AccountUserMembershipProvider",
                    accountUser.FirstName + " " + accountUser.LastName,
                    accountUser.ID,
                    accountUser.Email,
                    "",
                    "",
                    true,
                    false,
                    DateTime.Now,
                    DateTime.MinValue,
                    DateTime.MinValue,
                    DateTime.MinValue,
                    DateTime.MinValue);

        // Fill additional properties
        user.ID = accountUser.ID;
        user.Email = accountUser.Email;
        user.FirstName = accountUser.FirstName;
        user.LastName = accountUser.LastName;
        user.Password = accountUser.Password;
        user.MediaID = accountUser.MediaID;
        user.Media = accountUser.Media;
        user.Identity = accountUser.Identity;
        user.CreatedAt = accountUser.CreatedAt;
        user.UpdatedAt = accountUser.UpdatedAt;

        UpdateCookie(user.Email);
    }
    private static void UpdateCookie(string email)
    {
        HttpCookie cookie = FormsAuthentication.GetAuthCookie(email, true);
        var ticket = FormsAuthentication.Decrypt(cookie.Value);

        // Store UserData inside the Forms Ticket with all the attributes
        // in sync with the web.config
        var newticket = new FormsAuthenticationTicket(ticket.Version,
                                                      ticket.Name,
                                                      ticket.IssueDate,
                                                      ticket.Expiration,
                                                      true, // always persistent
                                                      email,
                                                      ticket.CookiePath);

        // Encrypt the ticket and store it in the cookie
        cookie.Value = FormsAuthentication.Encrypt(newticket);
        cookie.Expires = newticket.Expiration.AddHours(24);
        HttpContext.Current.Response.Cookies.Set(cookie);
    }

现在显然这只是创建一个新实例而不是更新现有实例,这不允许我在不注销并重新登录的情况下查看更新的详细信息。有什么想法吗?

编辑 所以我设法找到了其他人使用他们自己的自定义更新方法的示例,但他们似乎所做的只是更新数据库而不是 MembershipUser 本身。我已经在做这个了?!

我试图改为只更新 FormsAuthenticationCookie,然后在调用 Membership.GetUser() 时我至少传递了更新的 User.Identity.Name,但无济于事,即使数据库已更新,数据仍然是旧数据。我 运行 没主意了...

这可能是昨天问题的重复MembershipUser not getting updated result from database

我最终发现 MembershipUser 没有更新,因为每次调用 GetUser() 时所涉及的查询都在使用 FirstOrDefault()。事实证明,这会缓存结果而不是检索新结果。通过将 AsNoTracking() 添加到查询本身,我现在可以获得更新的结果,甚至不必调用 UpdateUser()。