我在 MVC4 应用程序中使用 SimpleMembership,需要用户能够更改自己的用户名。
我有这个功能,所以当用户更改他们的用户名时它可以工作。但是,当调用诸如 Roles.IsUserInrole() 之类的东西时,它会失败,因为 User.Identity.Name 设置为他们登录的内容,而不是新值。该值不再存在于数据库中,因为他们已更改名称。
我看不到用用户名更新登录用户上下文的方法。大多数情况下,我可以将用户 ID 存储在 session 中并在查询时检索它,但我使用 Roles 方法在失败的 View 中显示数据。
有什么想法吗?
谢谢!
最佳答案
这是我当前(有效)的解决方案:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(AccountEditModel model)
{
if (ModelState.IsValid)
{
if (HasSensitiveInformationChanged(model)) // model.EmailAddress.ToLower() != User.Identity.Name.ToLower()
{
if (Membership.ValidateUser(User.Identity.Name, model.Password)) // && WebSecurity.IsCurrentUser(User.Identity.Name)) //redundant?
{
using (UsersContext db = new UsersContext())
{
UserProfile user = db.UserProfiles.FirstOrDefault(u => u.EmailAddress.ToLower() == User.Identity.Name.ToLower());
if (user != null)
{
user.EmailAddress = model.EmailAddress;
db.SaveChanges();
WebSecurity.Logout();
WebSecurity.Login(model.EmailAddress, model.Password);
return RedirectToAction("Index", "Search");
}
else
{
ModelState.AddModelError("", "Could not find user. Please try logging in again.");
}
}
}
else
{
ModelState.AddModelError("","Could not change email address. Please verify your password and try again.");
}
}
else
{
//no change
return RedirectToAction("Index", "Search");
}
}
return View("Index", model);
}
关于c# - SimpleMembership 更改用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15171226/