User.Identity.Name全名mvc5

时间:2014-01-26 11:23:08

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

我通过在ApplicationUser类中添加少量字段来扩展ASP NET标识架构,该字段派生自IdentityUser。我添加的字段之一是FullName

现在,当我写User.Identity.Name时,它会给我用户名,我正在寻找像User.Identity.FullName这样的东西,它应该返回我添加的FullName。

不确定,如何实现这一点,我们将非常感谢任何指导。

感谢。

8 个答案:

答案 0 :(得分:22)

您可以在创建用户时将其添加到用户的声明中,然后将其作为来自User.Identity的声明进行检索:

await userManager.AddClaimAsync(user.Id, new Claim("FullName", user.FullName));

退却:

((ClaimsIdentity)User.Identity).FindFirst("FullName")

或者您可以直接获取用户并从user.FullName访问它:

var user = await userManager.FindById(User.Identity.GetUserId())
return user.FullName

答案 1 :(得分:21)

在ApplicationUser类中,您会注意到一条评论(如果您使用标准MVC5模板),其中显示“在此处添加自定义用户声明”。

鉴于此,这是添加FullName的样子:

public class ApplicationUser : IdentityUser
{
    public string FullName { get; set; }

    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("FullName", this.FullName));
        return userIdentity;
    }
}

使用此功能,当有人登录时,FullName声明将被放入cookie中。您可以像这样帮助访问它:

    public static string GetFullName(this System.Security.Principal.IPrincipal usr)
    {
        var fullNameClaim = ((ClaimsIdentity)usr.Identity).FindFirst("FullName");
        if (fullNameClaim != null)
            return fullNameClaim.Value;

        return "";
    }

并使用这样的帮助:

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

请注意,自定义用户声明存储在Cookie中,这比从数据库获取用户信息更好...为常用数据保存数据库命中。

答案 2 :(得分:9)

我发现这很好用

<强>的AccountController:

private async Task SignInAsync(ApplicationUser user, bool isPersistent)
    {
        AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
        var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
        identity.AddClaim(new Claim("FullName", user.FullName));
        identity.AddClaim(new Claim("Email", user.Email));
        identity.AddClaim(new Claim("DateCreated", user.DateCreated.ToString("MM/dd/yyyy")));
        AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
    }

身份的扩展方法:

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

在您的视图中

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

你可以在这里看一下这个主题: Link

答案 3 :(得分:3)

可以通过定义您自己的IIdentity(也可能是IPrincipal)并在为HTTP请求创建IPrincipal时构建它(当引发PostAuthenticateRequest时)。

如何实施自己的IIDentityIPrincipalHow do I implement custom Principal and Identity in ASP.NET MVC?

答案 4 :(得分:2)

我通过执行以下操作解决了问题:

1 - 通过扩展IPrincipal

创建我自己的CustomPrincipal

2 - 在每个请求经过身份验证后加载CustomPrincipal。

创建我自己的CustomPrincipal

interface ICustomPrincipal : IPrincipal
{
    string UserId { get; set; }
    string FirstName { get; set; }
    string LastName { get; set; }
    int CustomerId { get; set; }
}

public partial class CustomPrincipal : ClaimsPrincipal, ICustomPrincipal
{
    #region IPrincipal Members
    public new ClaimsIdentity Identity { get; private set; }
    public new bool IsInRole(string role)
    {
        IdentityManager manager = new IdentityManager();
        return manager.IsInRole(role, this.UserId);
    }
    #endregion

    public CustomPrincipal(ApplicationUser user, IIdentity identity)
        :base(identity)
    {
        this.Identity = new ClaimsIdentity(identity);
        this.UserId = user.Id;
        this.FirstName = user.FirstName;
        this.LastName = user.LastName;
        this.CustomerId = user.CustomerId;
        this.DateCreated = user.DateCreated;
    }

    #region ICustomPrinicpal Members
    public string UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int CustomerId { get; set; }
    public DateTime DateCreated { get; set; }
    #endregion

    public string GetFullName()
    {
        return this.FirstName + " " + this.LastName;
    }
}

在每个请求经过身份验证后加载CustomPrincipal

在Global.asax.cs中......

    protected void Application_PostAuthenticateRequest(object sender, EventArgs e)
    {
        if (User.Identity.IsAuthenticated)
        {
            //At this point we need to get the user from the database based on the username. 
            ApplicationUser AppUser = ApplicationUserDB.GetByUserName(User.Identity.Name);
            CustomPrincipal UserPrincipal = new CustomPrincipal(AppUser, User.Identity);
            HttpContext.Current.User = UserPrincipal;
        }
    }

正如您在上面的代码中所看到的,我检索ApplicationUser并将其传递给CustomPrincipal的构造函数。然后我将新CustomPrincipal分配给当前上下文。

答案 5 :(得分:1)

将值存储到声明并阅读。

商店价值

public class ApplicationUser : IdentityUser
{
    public string FullName { get; set; }

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

        userIdentity.AddClaim(new Claim("FullName", this.FullName));

        return userIdentity;
    }
}

读取值

var FullName = "";
if (User != null)
{
    var identity = (System.Security.Claims.ClaimsIdentity)Context.User.Identity;
    var claim1 = identity.Claims.FirstOrDefault(c => c.Type == "FullName");
    if (claim1 != null)
    {
        FullName = claim1.Value;
    }
}

答案 6 :(得分:0)

这应该可以解决问题:

User.Claims.Single(x => x.Type== "name").Value

答案 7 :(得分:0)

我尝试过了,而且行得通!

IdentityModels.cs / ApplicationUser类

// Add custom user claims here
        userIdentity.AddClaim(new Claim("FullName", this.FullName));

_LoginPartialView

    <li>
@Html.ActionLink("Hello " +  (((ClaimsIdentity)User.Identity).FindFirst("FullName").Value) + " !", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
    </li>