.Net Core : Extend Identity User and add custom field in AspNetUsers table
Create new class and inherit with IdentityUser, here I created "ApplicationUser" and added
namespace DotNetCodeDemo.Repository.Models
{
public class ApplicationUser : IdentityUser
{
public string City { get; set; }
public string MobileNumber { get; set; }
public DateTime BirthDate { get; set; }
public DateTime JoinDate { get; set; }
}
}
Update dbContext class
namespace DotNetCodeDemo.Repository
{
public class AppDbContext : IdentityDbContext<ApplicationUser>
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
public DbSet<Employee> Employees { get; set; }
public DbSet<Department> Departments { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Seed();
}
}
}
Update ConfigureServices method in startup class
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContextPool<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DotNetCoreDB")));
services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
options.Password.RequiredLength = 10; // if you want to set your own password strength rule
options.Password.RequiredUniqueChars = 2;
}).AddEntityFrameworkStores<AppDbContext>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddScoped<IEmployeeRepository, EmployeeRepository>();
}
Update IdentityUser with ApplicationUser in your controller
namespace DotNetCodeDemo.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AccountController : Controller
{
private readonly UserManager<ApplicationUser> userManager;
private readonly SignInManager<ApplicationUser> signInManager;
public AccountController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
{
this.userManager = userManager;
this.signInManager = signInManager;
}
[HttpPost]
[Route("Register")]
public async Task<JsonResult> Post(VMRegister vmRegister)
{
IdentityResult result = new IdentityResult();
string errorMessage = "success";
if(ModelState.IsValid)
{
var user = new ApplicationUser
{
UserName = vmRegister.Email,
Email = vmRegister.Email,
City = vmRegister.City
};
result = await userManager.CreateAsync(user, vmRegister.Password);
if(result.Succeeded)
{
//to Signin user
//signInManager.SignInAsync(user, isPersistent: false).Start();
}
else
{
if(result.Errors.Count() > 0)
{
errorMessage = "";
foreach (var error in result.Errors)
{
errorMessage += error.Description;
}
}
}
}
return Json(new { id = "1", message = errorMessage });
}
}
}
Hope this will help you and save your time.
Enjoy !!!
:)
No comments:
Post a Comment