identity 2.0 _登录部分的名字

本文关键字:登录部 identity | 更新日期: 2023-09-27 18:19:51

我的应用程序是MVC5 c#,我已经将ApplicationUser模型扩展为包括名字和姓氏,运行良好。我正试图弄清楚如何更改loginPartial以在以下代码中显示用户的实际名字而不是他们的电子邮件地址:

@Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Manage", "Account", routeValues: null, htmlAttributes: new { title = "Manage" })

identity 2.0 _登录部分的名字

以上是我的问题,很遗憾我无法使用旧帐户登录。我是怎么做到的:

在账户管理员/登录中,我添加了以下内容:

            var user = await UserManager.FindByNameAsync(model.UserName);
            var t = await UserManager.AddClaimAsync(user.Id, new Claim("FullName", user.FirstName + " " + user.LastName));

添加此类:

public static class GenericPrincipalExtensions
    {
    public static string FullName (this IPrincipal user)
        {
        if (user.Identity.IsAuthenticated)
            {
            var claimsIdentity = user.Identity as ClaimsIdentity;
            if (claimsIdentity != null)
                {
                foreach (var claim in claimsIdentity.Claims)
                    {
                    if (claim.Type == "FullName")
                        return claim.Value;
                    }
                }
            return "";
            }
        else
            return "";
        }
    }

请看上面布伦丹·格林的评论,感谢布伦丹的领导。将登录部分更改为:(_L)

 @Html.ActionLink("Hello " + User.FullName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new {title = "Manage" })

通过添加GivenName声明类型,您应该能够非常容易地做到这一点。此代码是使用默认的mvc5/web应用程序visualstudio模板创建和测试的,该模板使用asp.net标识2。

AccountController.cs

    //
    // POST: /Account/Login
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            var user = await UserManager.FindAsync(model.UserName, model.Password);
            if (user != null)
            {
                await SignInAsync(user, model.RememberMe);
                //Add the Full name claim, or any other potential claim information.
                var userClaims = User as ClaimsPrincipal;
                var identity = userClaims.Identity as ClaimsIdentity;
                identity.AddClaim(new Claim(ClaimTypes.GivenName, user.FullName));
                return RedirectToLocal(returnUrl);
            }
            else
            {
                ModelState.AddModelError("", "Invalid username or password.");
            }
        }
        // If we got this far, something failed, redisplay form
        return View(model);
    }

_LoginPartial.cs.html

@Html.ActionLink("Hello " + System.Security.Claims.ClaimsPrincipal.Current.FindFirst(System.IdentityModel.Claims.ClaimTypes.GivenName).Value + "!", "Manage", "Account", routeValues: null, htmlAttributes: new { title = "Manage" })

注意,像这样的代码可能会变得很麻烦,所以您可以创建一个扩展方法来获得名称并看起来更干净。