asp.net 查看页面中的身份声明全名

asp.net identity claim fullname in view page

我是 asp.net Identity 2.0 的新手,我想在 Razor 视图页面中显示我的全名而不是用户名。

所以我向 IdentityUser 添加了新的 属性。

public class ApplicationUser : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string FullName => $"{FirstName} {LastName}";
}

默认 AccountController 包含登录方法:

    [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, string returnUrl)
    {           
        var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, 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", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "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 table 中创建数据库条目。如果你想这样做,那么你必须在 PasswordSignInAsync 之前添加声明 (await UserManager.AddClaimAsync(user.Id, new Claim("FullName", user.FullName));) 并且在我看来不在登录操作中。它最好在您添加和更新用户的名字和姓氏的操作中。

另一种方法是在登录时生成 ClaimsIdentity 时添加此数据。在您的自定义 IdentityUser class 中有一个 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;
    }
}