How to save new record with hashed password in my custom table instead of aspnet user?

后端 未结 1 806
情话喂你
情话喂你 2021-01-17 13:00

I am using asp.net identity to create new user but getting error:

Cannot insert the value NULL into column \'Id\', table \'Mydb.dbo.AspNetUsers\'; c

相关标签:
1条回答
  • 2021-01-17 13:11

    The inconsistency i found, in ApplicationUser class you are declaring property Idand Email which is wrong because the IdentityUser class already have those properties. This may arise the issue. But you can override them if necessary. Also the constructor you are using isn't necessary. The ApplicationUser class should be:

    public class ApplicationUser : IdentityUser
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            this.SecurityStamp = Guid.NewGuid().ToString();
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
    
        public string FirstName { get; set; }
        public string LastName { get; set; }    
        public string Password { get; set; }
        public string Role { get; set; }
        public bool? IsActive { get; set; }
        public int? CreatedBy { get; set; }
        public DateTime? CreatedDate { get; set; }
        public DateTime? LastLogin { get; set; }
    
    }
    

    Second thing, you are creating the user inside Login action which is also not valid. you should do it inside Register action. Following in an example:

     public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
              var user = new ApplicationUser
                {
                    FirstName = "Abc",
                    LastName = "Pqr",
                    UserName = "Abc@yahoo.com",
                    Email= model.Email,
                    Password= model.Password,
                    PasswordHash = UserManager.PasswordHasher.HashPassword(model.Password),
                    SecurityStamp = Guid.NewGuid().ToString()
                };
    
                var result = await UserManager.CreateAsync(user);
            if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);                    
                    return RedirectToAction("Index", "Home");
                }
                AddErrors(result);
            }
    
            return View(model);
        }
    

    Hope this will help :)

    0 讨论(0)
提交回复
热议问题