我是asp.net Identity 2.0的新手,我想在用户名的Razor视图页面中显示我的FullName.
public class ApplicationUser : IdentityUser { public string FirstName { get; set; } public string LastName { get; set; } public string FullName => $"{FirstName} {LastName}"; }
[HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> Login(Loginviewmodel model,string returnUrl) { var result = await SignInManager.PasswordSignInAsync(model.Email,model.Password,model.RememberMe,shouldLockout: false); switch (result) { case SignInStatus.Success: return RedirectToLocal(returnUrl); case SignInStatus.LockedOut: return View("Lockout"); case SignInStatus.Requiresverification: return RedirectToAction("SendCode",new { ReturnUrl = returnUrl,RememberMe = model.RememberMe }); case SignInStatus.Failure: default: ModelState.AddModelError("","Invalid login attempt."); return View(model); } }
public async Task<ActionResult> Login(Loginviewmodel model,shouldLockout: false); //------------------------------------------------------- if (result == SignInStatus.Success) { var user = await UserManager.FindByEmailAsync(model.Email); if (user != null) { await UserManager.AddClaimAsync(user.Id,new Claim("FullName",user.FullName)); } } //-------------------------------------------------------- switch (result) { case SignInStatus.Success: return RedirectToLocal(returnUrl); case SignInStatus.LockedOut: return View("Lockout"); case SignInStatus.Requiresverification: return RedirectToAction("SendCode","Invalid login attempt."); return View(model); } }
我创建了一个从Razor视图读取FullName的扩展方法:
public static class IdentityExtensions { public static string GetFullName(this IIdentity identity) { var claim = ((ClaimsIdentity) identity); return claim.FindFirst("FullName"); } }
但FullName总是来的Null
<ul class="nav navbar-nav navbar-right"> <li> @Html.ActionLink("Hello " + User.Identity.GetFullName() + "!","Index","Manage",routeValues: null,htmlAttributes: new { title = "Manage" }) </li> <li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li> </ul>
解决方法
您尝试添加声明的方式是在UserClaims表中创建数据库条目.如果你想这样做,那么你必须在PasswordSignInAsync之前添加声明(等待UserManager.AddClaimAsync(user.Id,new Claim(“FullName”,user.FullName));),在我看来不是在Login动作中.在您添加和更新用户的FirstName和LastName的操作中更好.
另一种方法是在登录时生成ClaimsIdentity时添加此数据.在您的自定义IdentityUser类中,有一个GenerateUserIdentityAsync方法,您可以在其中简单地:
public class ApplicationUser : IdentityUser { public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) { // Note the authenticationType must match the one defined in CookieAuthenticationoptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this,DefaultAuthenticationTypes.ApplicationCookie); // Add custom user claims here userIdentity.AddClaim(new Claim("LastName",$"{FirstName} {LastName}")); return userIdentity; } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。