【问题标题】:asp.net identity claim fullname in view page视图页面中的 asp.net 身份声明全名
【发布时间】:2016-06-29 04:45:20
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    您尝试添加声明的方式是在UserClaims 表中创建数据库条目。如果你想这样做,那么你必须在PasswordSignInAsync 之前添加声明(await UserManager.AddClaimAsync(user.Id, new Claim("FullName", user.FullName));),我认为不是在登录操作中。在您添加和更新用户的名字和姓氏的操作中更好。

    另一种方法是在登录时生成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;
        }
    }
    

    【讨论】:

    • 我想在网页顶部显示用户全名。我的 AspNetUsers 表包含数据库中的 FirstName 和 LastName 列。
    • 你试过我建议的第二种方法了吗?
    猜你喜欢
    • 2016-03-01
    • 1970-01-01
    • 2021-08-26
    • 2014-02-28
    • 1970-01-01
    • 2012-02-25
    • 2016-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多