使用Microsoft MVC 5和Identities 3.0.0 rc1-final时,我遇到了一个问题。
因此,我修改了AppUser.cs模型,该模型扩展了IdentityUser以包含FirstName和LastName列。我的下一个目标是为存储FullName的用户创建声明,FullName是Firstname和Lastname的连接。我在为数据库播种时成功完成了这项工作。当用户通过更改名称来修改配置文件时,我也可以成功更新数据库。当用户对该个人资料进行更改时,我想更新" FullName"在数据库声明表和用户cookie中声明,以便我可以在页面标题中显示全名。问题是我似乎无法将数据保存到表中。我可以更新User对象中的声明,但有关它的更新。我已经研究并尝试了十几种不同的东西,但似乎并没有解决我的问题,下面是我的一些代码:
AppUser.cs Model
public class AppUser : IdentityUser {
[StringLength(255)]
public string FirstName { get; set; }
[StringLength(255)]
public string LastName { get; set; }
}
助手类。这是我的研究得出的结果this post.我意识到我错过了他的方法的一部分,最后两行,但在调用身份验证管理器时我永远无法解决编译错误。
public static void AddUpdateClaim(this IPrincipal currentPrincipal, string key, string value) {
var identity = currentPrincipal.Identity as ClaimsIdentity;
if (identity == null)
return;
// check for existing claim and remove it
var existingClaim = identity.FindFirst(key);
if (existingClaim != null)
identity.RemoveClaim(existingClaim);
// add new claim
identity.AddClaim(new Claim(key, value));
}
ManageController,这是更新用户个人资料的post方法:
public async Task<IActionResult> Index(IndexViewModel model) {
if (!ModelState.IsValid) {
return View(ModelState);
}
var user = await base.GetCurrentUserAsync();
if (user != null) {
user.Email = model.Email;
user.FirstName = model.FirstName;
user.LastName = model.LastName;
User.AddUpdateClaim("FullName", "Test User");
var result = await _userManager.UpdateAsync(user);
if (result.Succeeded) {
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.AccoutUpdated });
} else {
_logger.LogError(1, "Error updating user: {username}", user.UserName);
base.AddErrors(result);
return View(model);
}
}
// If we got this far, something failed, redisplay form with errors.
return View(model);
}
在这一点上的任何帮助都会非常感激,因为我已经在这墙上撞了一会儿了!
答案 0 :(得分:0)
我几天前想到了这一点......基本上我过于复杂了。 :P