加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 09:42:05 所属栏目:asp.Net 来源:网络整理
导读:我是asp.net Identity 2.0的新手,我想在用户名的Razor视图页面中显示我的FullName. 所以我向IdentityUser添加了新属性. public class ApplicationUser : IdentityUser{ public string FirstName { get; set; } public string LastName { get; set; } public
我是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,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;
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读