视图页面中的asp.net标识声明全名

时间:2016-03-14 08:23:48

标签: asp.net asp.net-mvc-4 razor asp.net-mvc-5 asp.net-identity-2

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

所以我在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总是空无一人

<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>

1 个答案:

答案 0 :(得分:1)

您尝试添加声明的方式是在UserClaims表中创建数据库条目。如果您要执行此操作,则必须在await UserManager.AddClaimAsync(user.Id, new Claim("FullName", user.FullName));之前添加声明(PasswordSignInAsync),我认为不在登录操作中。在您添加和更新用户的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;
    }
}