Search code examples
asp.netasp.net-identity-2

Cast User object in ASP.NET Identity 2.0


I want to get a custom ApplicationUser instance in the controller. Can I get it from User object inside the controller? How should I do that?

I tried this but it didn't worked:

ApplicationUser u = (ApplicationUser)User;
ApplicationUser u2 = (ApplicationUser)User.Identity;

My custom Identity models are like that:

public class ApplicationUser : IdentityUser<long, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
{
    public virtual UserInfo UserInfo { get; set; }

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(ApplicationUserManager 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
        return userIdentity;
    }

}

public class ApplicationRole : IdentityRole<long, ApplicationUserRole>
{
    public ApplicationRole() : base() { }
    public ApplicationRole(string name, string description)
    {
        this.Name = name;
        this.Description = description;
    }
    public virtual string Description { get; set; }
}

public class ApplicationUserRole : IdentityUserRole<long> { }
public class ApplicationUserClaim : IdentityUserClaim<long> { }

public class ApplicationUserLogin : IdentityUserLogin<long> { }

Solution

  • No. The User property of the controller returns an IPrincipal object, not an ApplicationUser object. These are two entirely different things. IPrincipal is used by ASP.NET to control authentication and authorization, while ApplicationUser is merely an entity used in your database.

    If you want ApplicationUser, you have to get it from UserManager.