我已覆盖成员资格方法以创建自定义成员资格.
在帐户模型中,我重写了CreateUser方法:
public override MembershipUser CreateUser(string username,string password,string email,string passwordQuestion,string passwordAnswer,bool isApproved,object providerUserKey,out MembershipCreateStatus status) { ValidatePasswordEventArgs args = new ValidatePasswordEventArgs( username,password,true); OnValidatingPassword(args); if (args.Cancel) { status = MembershipCreateStatus.InvalidPassword; return null; } if (RequiresUniqueEmail && GetUserNameByEmail(email) != "") { status = MembershipCreateStatus.DuplicateEmail; return null; } MembershipUser u = GetUser(username,false); if (u == null) { UserRepository _user = new UserRepository(); // Here I call my new method which has fields I've created in the // User table; I'm using entity framework. _user.CreateUser(username,email); status = MembershipCreateStatus.Success; return GetUser(username,false); } else { status = MembershipCreateStatus.DuplicateUserName; } return null; } public MembershipUser CreateUser(string username,string email) { using (CustomMembershipDB db = new CustomMembershipDB()) { User user = new User(); user.UserName = username; user.Email = email; user.PasswordSalt = CreateSalt(); user.Password = CreatePasswordHash(password,user.PasswordSalt); user.CreatedDate = DateTime.Now; user.IsActivated = false; user.IsLockedOut = false; user.LastLockedOutDate = DateTime.Now; user.LastLoginDate = DateTime.Now; //Generate an email key // user.NewEmailKey = GenerateKey(); db.AddToUsers(user); db.SaveChanges(); //send mail // SendMail(user); return GetUser(username); } }
解决方法
您可以保留AspNetUsers表,并创建一个新表来存储额外信息(链接到原始信息).这样您就不会破坏成员资格提供程序中的任何现有代码.
最初的AspNetUsers表有:
[ID],[电子邮件],[EmailConfirmed],[PasswordHash],[SecurityStamp],[******中国],[PhoneNumberConfirmed],[TwoFactorEnabled],[LockoutEndDateUtc],[LockoutEnabled],[AccessFailedCount],[用户名]
用于存储额外数据的新表可以具有例如:
[Id],[UserId] [DateOfBirth],[传记]等
其中[UserId]是AspNetUsers表的外键.
这种方法的一个优点是,您可以创建多种类型的用户,每种用户将相关信息存储在不同的表中,而常用数据仍在原始表中.
如何:
>首先更新Registerviewmodel以包含所需的额外数据.
>更新帐户控制器中的Register方法,这是使用代码更新的原始方法,以插入新的配置文件数据:
[HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> Register(Registerviewmodel model) { if (ModelState.IsValid) { var user = new ApplicationUser() { UserName = model.Email,Email = model.Email }; IdentityResult result = await UserManager.CreateAsync(user,model.Password); if (result.Succeeded) { // Start of new code ---------------------------------------- // Get Id of newly inserted user int userId = user.Id; // Get Id of newly inserted user // Create a profile referencing the userId AddUserProfile(userId,model); // End of new code ---------------------------------------- await SignInAsync(user,isPersistent: false); return RedirectToAction("Index","Home"); } else { AddErrors(result); } } return View(model); }
>根据需要实现AddUserProfile(int userId,Registerviewmodel模型)方法.您将从模型对象中获取额外数据以及userId,并将新的配置文件对象保存在数据库中.