如何自定义实现asp.net身份的UpdateAsync方法?

我正在做自定义asp.net身份而不使用asp.net内置表。我已成功创建用户实现自定义CreateAsync

现在我想用新的加密密码更新用户,所以我没有得到如何提供UpdateAsync method自定义实现。

这是我的表:

用户Id,Name,EmailId,Password,Statistics,Salary

型号

 public class UserModel : IUser { public string Id { get; set; } public string Name { get; set; } public string EmailId { get; set; } public string Password { get; set; } public int Salary { get; set; } } 

我实现IUserstore的自定义类:

 public class UserStore : IUserStore, IUserPasswordStore { private readonly MyEntities _dbContext; private readonly HttpContext _httpContext; // How to implement this method for updating only user password public Task UpdateAsync(UserModel user) { throw new NotImplementedException(); } public Task CreateAsync(UserModel user) { return Task.Factory.StartNew(() => { HttpContext.Current = _httpContext ?? HttpContext.Current; var user = _dbContext.User.Create(); user.Name = user.Name; user.EmailId = user.EmailId; user.EmailAddress = user.Email; user.Password = user.Password; _dbContext.Users.Add(dbUser); _dbContext.SaveChanges(); }); } public Task SetPasswordHashAsync(UserModel user, string passwordHash) { return Task.Factory.StartNew(() => { HttpContext.Current = _httpContext ?? HttpContext.Current; var userObj = GetUserObj(user); if (userObj != null) { userObj.Password = passwordHash; _dbContext.SaveChanges(); } else user.Password = passwordHash; }); } public Task GetPasswordHashAsync(UserModel user) { //other code } } 

控制器:

 public class MyController : ParentController { public MyController() : this(new UserManager(new UserStore(new MyEntities()))) { } public UserManager UserManager { get; private set; } [HttpPost] public async Task SaveUser(UserModel userModel) { IdentityResult result = null; if (userModel.Id > 0) //want to update user with new encrypted password result = await UserManager.UpdateAsync(user); else result = await UserManager.CreateAsync(userModel.EmailId, userModel.Password); } } 

不确定这是不是你要找的……

  public Task UpdateAsync(UserModel model) { return Task.Factory.StartNew(() => { var user = _dbContext.User.Find(x => x.id == model.id); user.Password = model.Password; _dbContext.SaveChanges(); }); } 

它将获取特定记录并更新密码,然后保存记录。

编辑

由于密码没有加密,我添加了代码来获取该字符串并保持模型原样,这个扩展方法将加密密码的值,我没有测试这个,但我相信它会工作。

  user.Password = model.Password.EncryptPassword(EncryptKey); 

加密密码的扩展方法

不久之后,我在.NET Identity上创建了一个完整的包装器,可以在这里找到代码。 它可能对你有所帮助。 你也可以在这里找到nuget。 我还在这里的博客中解释了这个库。