我正在做自定义的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<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
}
}
控制器:
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)
{
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);
Extension methods to encrypt password
关于c# - 如何赋予asp.net身份UpdateAsync方法的自定义实现?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39275597/