我对 MVC5/ASP.NET Identity 相当陌生,我发现了一个有点困扰我的问题。
我正在为我的 ASP.NET MVC5 应用程序编写一个小表单,该表单将允许管理员用户(管理员角色的成员)查看已注册到该网站的用户并编辑其详细信息并为其分配角色用户。提交表单时,如果已将角色分配给用户,则调用 UserManager.AddToRole 方法。
我注意到,一旦完成此操作,该用户就无法登录该应用程序。查看数据库,发现调用 AddToRole 时,PasswordHash 字段设置为 null。这是正常现象吗?如果不正常,我该如何解决这个问题?
作为引用,我的相关代码如下
Controller
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = "Admin")]
public ActionResult Details(EditUserViewModel model)
{
model.Save();
return RedirectToAction("List", "Account");
}
相关 View 模型
public class EditUserViewModel
{
public string UserId { get; set; }
public string UserName { get; set; }
[Required]
[StringLength(255)]
[Display(Name = "Email address")]
public string Email { get; set; }
[StringLength(255)]
[Display(Name = "First name")]
public string FirstName { get; set; }
[StringLength(255)]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[StringLength(255)]
[Display(Name = "Mobile Number")]
public string MobileNumber { get; set; }
public IList<EditUserRolesViewModel> UserRoles { get; set; }
public void Save()
{
using (ApplicationDbContext context = new ApplicationDbContext())
{
ApplicationUser user = new ApplicationUser()
{
Id = this.UserId,
UserName = this.UserName,
Email = this.Email,
FirstName = this.FirstName,
LastName = this.LastName,
MobileNumber = this.MobileNumber
};
context.Users.Attach(user);
context.Entry(user).Property(x => x.Email).IsModified = true;
context.Entry(user).Property(x => x.FirstName).IsModified = true;
context.Entry(user).Property(x => x.LastName).IsModified = true;
context.Entry(user).Property(x => x.MobileNumber).IsModified = true;
context.SaveChanges();
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
foreach (var row in this.UserRoles)
{
if (row.RowChanged)
{
if (row.RoleAssigned)
{
UserManager.AddToRole(this.UserId, row.RoleName);
}
else
{
UserManager.RemoveFromRole(this.UserId, row.RoleName);
}
}
}
}
}
}
public class EditUserRolesViewModel
{
public string RoleId { get; set; }
[Display(Name = "Role name")]
public string RoleName { get; set; }
[Display(Name = "Assigned")]
public bool RoleAssigned { get; set; }
public bool RowChanged { get; set; }
}
最佳答案
正如我从您的代码中看到的,您已附加部分初始化的对象 user
至context.Users
。结果当UserManager
获得控制权:AddToRole
,它尝试更新数据库。当前用户行中将有很多空字段或 null 字段。
您可以执行以下任一操作(两者都会有帮助):
而不是
ApplicationUser user = new ApplicationUser()
使用
user = UserManager.FindById(UserId)
从 View 模型分配值后,EntityFramework 将处理修改后的字段。处理角色时使用另一个上下文
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
关于asp.net - 调用 UserManager.AddToRole 会删除用户密码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24605240/