UserManager 包含 AddPasswordAsync
和 SetPhoneNumberAsync
等函数。
我为注册用户时未设置其值的 FirstName 和 LastName 添加了属性,因此我想添加屏幕来管理这些值(设置和更改它们)。
如何扩展用户管理器以添加像AddNamesAsync
这样的函数来执行此操作?
当我们评估管理控制器操作时,这样的函数变得必要,如下所示:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> SetPassword(SetPasswordViewModel model)
{
if (ModelState.IsValid)
{
var result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword);
if (result.Succeeded)
{
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return RedirectToAction("Index", new { Message = ManageMessageId.SetPasswordSuccess });
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
按照同样的逻辑,我想向控制器添加一个函数,如下所示:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> SetNames(SetUserFullNamesViewModel model)
{
if (ModelState.IsValid)
{
var result = await UserManager.AddNamesAsync(User.Identity.GetUserId(), model.FirstName, model.LastName);
if (result.Succeeded)
{
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
return RedirectToAction("Index", new { Message = ManageMessageId.SetNamesSuccess });
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
如何将函数添加到用户管理器或扩展用户管理器,以便我可以添加允许我更新用户添加和更新自定义属性值的函数?
首先将custom columns
添加到AppliicationUser
类
然后你可以像这样更新custom columns
[HttpPost]
public async Task<ActionResult> SetNames(SetUserFullNamesViewModel model)
{
ApplicationUser usermodel = UserManager.FindById(user.Id);
usermodel.Name = model.Name;
usermodel.Surname = model.Surname;
IdentityResult result = await UserManager.UpdateAsync(usermodel);
if (result.Succeeded)
{
return RedirectToAction("ListUser", "User");
}
return View();
}