Search code examples
asp.net-mvcasp.net-identityasp.net-core-mvc

How to create New user identity out side from Account controller?


I have merged my database with MVC asp.net Identity database and i want to creat a new user using asp.net identity from other controller ,but i could not successfully add the user even my code work without error this is the code:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Email,EmailConfirmed,Password,SecurityStamp,PhoneNumber,PhoneNumberConfirmed,TwoFactorEnabled,LockoutEndDateUtc,LockoutEnabled,AccessFailedCount,UserName")] AspNetUsers aspNetUsers)
{
    if (ModelState.IsValid)
    {
        //    ApplicationUserManager manager = new ApplicationUserManager(new UserStore<ApplicationUser>());

        //    var manager =   HttpContext.Current.GetOwinContext().GetUserManager<UserManager<User>>();
        var store = new UserStore<ApplicationUser>();
            var manager = new ApplicationUserManager(store);
            var user = new ApplicationUser() { Email = aspNetUsers.Email, UserName = aspNetUsers.UserName };
         var result=   manager.CreateAsync(user, aspNetUsers.PasswordHash);
        manager.Create(user, aspNetUsers.Password);
        //    db.AspNetUsers.Add(aspNetUsers);
        //    db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(aspNetUsers);
}

Solution

  • var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
    ApplicationUserManager _userManager = new ApplicationUserManager(store);
    var manger = _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
    var user = new ApplicationUser() { Email = aspNetUsers.Email, UserName = aspNetUsers.UserName };
    var usmanger= manger.Create(user, aspNetUsers.PasswordHash);