Search code examples
c#asp.net-coreasp.net-identityasp.net-core-webapi

.NET - Identity does not contain a definition for the custom field


I am working on a identity project, I am now trying to create an endpoint for getting the user profile. I want every profile to have a profile image.

I added the custom field in a new model class called User like this:

public class User : IdentityUser
    {
        public string? ProfileImage { get; set; }
    }

I also added in my startup.cs

services.AddIdentity<User, IdentityRole>()
                .AddEntityFrameworkStores<AppDbContext>()
                .AddDefaultTokenProviders();

And also in the AppDbContext

public class AppDbContext : IdentityDbContext<User>
    {

        public AppDbContext([NotNull] DbContextOptions options) : base(options) {}

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
        }
    }

I also have AutoMapper to map my UserDto with the User class.

However, in my AuthController where I am trying to create an endpoint to fetch the User with Id I get an error that IdentityUser does not contain a definition for ProfileImage.

[HttpGet("getUser/{id}")]
        public async Task<ActionResult> GetCurrentUser(string id)
        {
            var user = await userManager.FindByIdAsync(id);
            var model = new UserDto()
            {
                Id = user.Id,
                UserName = user.Email,
                Email = user.Email,
                ProfileImage = user.ProfileImage <--- error on this line
            };

            return Ok(model);
        }

What am I missing and what could I do to fix this?

Many thanks!


Solution

  • The issue here was that I put IdentityUser in the UserManager and SignInManager, instead I should have use my User class

    I changed from this

    private readonly UserManager<IdentityUser> userManager;
            private readonly SignInManager<IdentityUser> signInManager;
          
    
            public AuthController(UserManager<IdentityUser> userManager, 
                SignInManager<IdentityUser> signInManager)
            {
                this.userManager = userManager;
                this.signInManager = signInManager;
            }
    

    To this

    private readonly UserManager<User> userManager;
            private readonly SignInManager<User> signInManager;
           
            public AuthController(UserManager<User> userManager, 
                SignInManager<User> signInManager)
            {
                this.userManager = userManager;
                this.signInManager = signInManager;
            }