I am trying to implement IdentityFramework in my .NET Core 6 Web API Application.
Following is my settings.
public class ApplicationUser : IdentityUser<int>
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
My connection string is :
"ConnectionStrings": {
"connectionString": "Server=DESKTOP-HO7FAAD\\SQLEXPRESS; Database=AviaryDB; Trusted_Connection=True; MultipleActiveResultSets=true;"
}
Program.cs
builder.Services.AddIdentity<ApplicationUser, IdentityRole<int>>()
.AddEntityFrameworkStores<ApplicationDBContext>()
.AddDefaultTokenProviders();
builder.Services.AddDbContext<ApplicationDBContext>(db => db.UseSqlServer(builder.Configuration.GetConnectionString("connectionString")));
ApplicationDBContext.cs
public class ApplicationDBContext : IdentityDbContext<ApplicationUser, IdentityRole<int>, int>
{
public ApplicationDBContext(DbContextOptions<ApplicationDBContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
builder.Entity<ApplicationUser>(entity =>
{
entity.Property(p => p.Id).ValueGeneratedOnAdd();
entity.Property(p => p.FirstName).HasMaxLength(150);
entity.Property(p => p.LastName).HasMaxLength(150);
entity.ToTable(name: "Users");
});
builder.Entity<IdentityRole<int>>(entity =>
{
entity.Property(p => p.Id).ValueGeneratedOnAdd();
entity.ToTable(name: "Roles");
});
builder.Entity<IdentityUserRole<int>>(entity =>
{
entity.ToTable("UserRoles");
//in case you chagned the TKey type
entity.HasKey(key => new { key.UserId, key.RoleId });
});
builder.Entity<IdentityUserClaim<int>>(entity =>
{
entity.ToTable("UserClaims");
});
builder.Entity<IdentityUserLogin<int>>(entity =>
{
entity.ToTable("UserLogins");
//in case you chagned the TKey type
entity.HasKey(key => new { key.ProviderKey, key.LoginProvider });
});
builder.Entity<IdentityRoleClaim<int>>(entity =>
{
entity.ToTable("RoleClaims");
});
builder.Entity<IdentityUserToken<int>>(entity =>
{
entity.ToTable("UserTokens");
//in case you chagned the TKey type
entity.HasKey(key => new { key.UserId, key.LoginProvider, key.Name });
});
}
}
AccountController.cs
public class AccountController : ControllerBase
{
private readonly UserManager<ApplicationUser> _userManager;
public AccountController(
UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
[AllowAnonymous]
[HttpPost]
[Route("register")]
public async Task<ActionResult> Register([FromBody] RegisterModel model)
{
try
{
var userExists = await _userManager.FindByNameAsync(model.Username);
if (userExists != null)
return StatusCode(StatusCodes.Status500InternalServerError, new Response { Status = "Error", Message = "User already exists!" });
ApplicationUser user = new()
{
Email = model.Email,
SecurityStamp = Guid.NewGuid().ToString(),
UserName = model.Username,
};
var result = await _userManager.CreateAsync(user, model.Password);
if (!result.Succeeded)
return StatusCode(StatusCodes.Status500InternalServerError, new Response { Status = "Error", Message = "User creation failed! Please check user details and try again." });
return Ok("User created successfully!");
}
catch(Exception ex)
{
throw ex;
}
}
}
And I am getting the following error. Can anyone guide me what I am doing wrong?