我正在执行自定义 asp.net 标识,而不是使用 asp.net 内置表。我已通过实现自定义 CreateAsync
成功创建用户
现在我想用新的加密密码更新用户,所以我不知道如何提供 UpdateAsync 方法
的自定义实现。
这是我的 table :
用户:ID、姓名、电子邮件ID、密码、统计信息、薪资
型号:
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<UserModel>, IUserPasswordStore<UserModel>
{
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<string> GetPasswordHashAsync(UserModel user)
{
//other code
}
}
Controller :
public class MyController : ParentController
{
public MyController()
: this(new UserManager<UserModel>(new UserStore(new MyEntities())))
{
}
public UserManager<UserModel> UserManager { get; private set; }
[HttpPost]
public async Task<JsonResult> 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)
{
var user = _dbContext.User.Find(x => x.id == model.id);
user.Password = model.Password;
_dbContext.SaveChanges();
return Task.CompletedTask;
}
它将获取特定记录并更新密码,然后保存记录。
编辑
由于密码未加密,我添加了代码来获取该字符串并保留模型不变,此扩展方法将加密密码的值,我尚未对此进行测试,但我确信它会起作用。
user.Password = model.Password.EncryptPassword(EncryptKey);
关于c# - 如何自定义实现asp.net身份的UpdateAsync方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39275597/