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> { }
amp
  • 11,754
  • 18
  • 77
  • 133

1 Answers1

2

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.

Erik Funkenbusch
  • 92,674
  • 28
  • 195
  • 291
  • Ok. But I could save the information of the ApplicationUser using the Principal, as a cookie right? I don't want to query the database every time I need the user info. How could I do that? Can you point me to the right direction? – amp Jul 27 '14 at 19:15
  • 1
    @amp - what information do you need from the ApplicationUser? You would not want to save this object as a cookie, because it contains the users password hash, and this should never leave the server. – Erik Funkenbusch Jul 27 '14 at 20:05
  • @amp you can always store required information about the user in Claims. These are retrievable from `ClaimsPrincipal.Current` and this does not hit the DB. – trailmax Jul 28 '14 at 13:22
  • I found a solution using claims. – amp Jul 29 '14 at 18:52