How to Get Custom Property Value of the ApplicationUser in the ASP.Net MVC 5 View?

后端 未结 1 1112
忘掉有多难
忘掉有多难 2020-12-06 07:13

In the ASP.Net MVC 5, the ApplicationUser can be extended to have custom property. I have extended it such that it now has a new property called

相关标签:
1条回答
  • 2020-12-06 07:27

    Add the claim in ClaimsIdentity:

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

    Created an extention method to read DisplayName from ClaimsIdentity:

    public static class IdentityExtensions
    {
        public static string GetDisplayName(this IIdentity identity)
        {
            if (identity == null)
            {
                throw new ArgumentNullException("identity");
            }
            var ci = identity as ClaimsIdentity;
            if (ci != null)
            {
                return ci.FindFirstValue("DisplayName");
            }
            return null;           
        }
    }
    

    In your view use it like:

    User.Identity.GetDisplayName()
    
    0 讨论(0)
提交回复
热议问题