Search code examples
asp.net-mvcmodel-view-controllerasp.net-identityclaims-based-identity

Access User.Identity property extension from a View (Error)


I am trying to add an extended property to the User.Identity and have done so as follows:

In IdentityModel.cs I have added a field called EbrowAdmin:

    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("EbrowAdmin", EbrowAdmin.ToString()));

        return userIdentity;
    }

    public bool EbrowAdmin { get; set; }

I created a foler called Extensions in the Project folder and added a class called Extensions.cs:

    public static class Extensions
    {
        public static string GetEbrowAdmin(this IIdentity identity)
        {
            var claim = ((ClaimsIdentity)identity).FindFirst("EbrowAdmin");
            // Test for null to avoid issues during local testing
            return (claim != null) ? claim.Value : string.Empty;
        }
    }

Now I can access this new property from my controllers with:

User.Identity.GetEbrowAdmin();

However I can't access it from my Views with the same code:

@User.Identity.GetEbrowAdmin();

Any ideas what I am missing?


Solution

  • You need to tell your views about your extension. Just like normal C# code, views are unaware of any custom code until you include the code's namespace with a using directive.

    Try putting a using <YOURPROJECT>.<YOURNAMESPACE>.Extensions in either your direct view or your viewstart.cshtml