identity 2.0 _LoginPartial名字

时间:2014-08-29 01:32:38

标签: c# asp.net-mvc asp.net-identity

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

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

2 个答案:

答案 0 :(得分:1)

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

在帐户控制器/登录中,我添加了以下内容:

            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 "";
        }
    }

请看Brendan Green的上述评论,谢谢Brendan的领导。 将_LoginPartial更改为:

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

答案 1 :(得分:0)

通过添加GivenName声明类型,您应该可以相当轻松地完成此操作。此代码是使用使用asp.net identity 2的默认mvc5 / web应用程序Visual Studio模板创建和测试的。

<强> 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.cshtml

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

请注意,这样的代码可能会变得毛茸茸,因此您可以创建一个获取名称并且看起来更清晰的扩展方法。