我正在尝试掌握 ASP.NET MVC 5 中引入的新成员资格系统,但我遇到了一个小问题,我很确定您能帮我解决这个问题。
我要离开 this tutorial并为 ApplicationUser 引入了自定义属性,例如 Name、Surname、DOB 等。
但是,我没有创建用户,而是尝试更新当前登录的用户。我正在查看当前用于更改密码的 Controller 方法。
public async Task<ActionResult> Manage(ManageUserViewModel model)
{
string userId = User.Identity.GetUserId();
bool hasLocalLogin = await IdentityManager.Logins.HasLocalLoginAsync(userId);
ViewBag.HasLocalPassword = hasLocalLogin;
ViewBag.ReturnUrl = Url.Action("Manage");
if (hasLocalLogin)
{
if (ModelState.IsValid)
{
IdentityResult result = await IdentityManager.Passwords.ChangePasswordAsync(User.Identity.GetUserName(), model.OldPassword, model.NewPassword);
if (result.Success)
{
return RedirectToAction("Manage", new { Message = "Your password has been changed." });
}
else
{
AddErrors(result);
}
}
}
else
{
// User does not have a local password so remove any validation errors caused by a missing OldPassword field
ModelState state = ModelState["OldPassword"];
if (state != null)
{
state.Errors.Clear();
}
if (ModelState.IsValid)
{
// Create the local login info and link it to the user
IdentityResult result = await IdentityManager.Logins.AddLocalLoginAsync(userId, User.Identity.GetUserName(), model.NewPassword);
if (result.Success)
{
return RedirectToAction("Manage", new { Message = "Your password has been set." });
}
else
{
AddErrors(result);
}
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
例如,我将如何继续更新 ApplicationUser 的姓氏?我需要调用 DbContext 还是?
我希望我的问题很清楚。
最佳答案
探索 IdentityManager.Store.UserManagement
和 IdentityManager.Store.Users
.
ApplicationUser cUser = (ApplicationUser) await IdentityManager.Store.Users.FindByNameAsync(HttpContext.User.Identity.Name, new System.Threading.CancellationToken());
cUser.Surname = "New Something";
IdentityResult result1 = await IdentityManager.Store.SaveChangesAsync();
上面的代码只是一个例子。基本上你需要探索
Store
IdentityManage
的属性(property).
关于asp.net - MVC5 ApplicationUser 自定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19348966/