Search code examples
asp.netasp.net-mvcentity-frameworkasp.net-mvc-5asp.net-identity

Get Authenticated Identity User data in ASP.NET MVC


I Have created an ASP.NET Identity Entity Framework, and added a customer fields for Registration and Login funtions in ASP.NET Identity - MVC

identityModel.cs

  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
                return userIdentity;
            }
    
            //add custom fields
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public bool IsAdministrator { get; set; }
    
        }

 public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false)
        {
        }

        public DbSet<Property> Property { get; set; }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
    }

In another class called Property (after login and authentication passed)

I want to call on the one field in AspNetUsers table, which is the currently logged in. I want to check the IsAdministrator field and its values and do some conditions on what to view based on that value.

this is what I have done, but not successful

 public class PropertyController : Controller
    {
        private ApplicationDbContext db = new ApplicationDbContext();
        

        // GET: Property
        [Authorize]
        public async Task<ActionResult> Index()
        {

            var user = System.Web.HttpContext.Current.User.Identity.GetUserId();
            bool admin = db.Users.SingleOrDefault(y => y.Id.Equals("user")).IsAdministrator;
            //return View(await db.Property.ToListAsync());
            if (admin == true){
                return View(await db.Property.Where(x => x.PropertyID == 1).ToListAsync()); }
            else  {
                return View(await db.Property.ToListAsync());}
           
        }

I was able to extract the UserID of the currently logged-in user, but i want the another field or information from the user which is the IsAdmin field which is either 1 OR 0.

How can i achieve that?

this does not work

 bool admin = db.Users.SingleOrDefault(y => y.Id.Equals("user")).IsAdministrator;

error enter image description here


Solution

  • The expression SingleOrDefault(y => y.Id.Equals("user")) does not make any sense. It's going to search database a user with Id = "user" and finds nothing. That's why it returns null which causes the NullReferenceException.

    Try to use the following snippet

    ...
    var userId = System.Web.HttpContext.Current.User.Identity.GetUserName();
    var user = UserManager.FindByNameAsync(userId);
    var isAdmin = user.IsAdministrator;
    ...
    

    to get user