Search code examples
asp.netasp.net-mvcasp.net-coreasp.net-core-mvcasp.net-identity

Identity Framework Add User and use in same method


I have a call that will create a new user if they enter a password when purchasing the product. If they create an account I then have to update the data to be reflected to that user. But the problem I am having is I am not able to use that user in the same call and have not been able to figure out how to update the Identity Framework to be able to recognized the newly created user. If the page is refreshed and tried again it works, but the first time it creates an error... because there is no user.

It saves the data in the AspNetUsers table. The newUser object has an assigned user. But I am not able to use that object either. I tried pulling the newUser object out and assigning the newUser object but it then tries to create a new user with the same ID and I get foreign key errors. I am not sure how to make it so I can use the newly created user in the same call.

public async Task<IActionResult> CheckoutStep2(CheckoutStep2ViewModel model)

  if (model.Password != null && model.PasswordConfirm != null)
  {
    ApplicationUser newUser = new ApplicationUser { UserName = model.PaymentInformation.BillingEmail, Email = model.PaymentInformation.BillingEmail };
    var result = await userManager.CreateAsync(newUser, model.Password);
    if (result.Succeeded)
    {
      await signInManager.SignInAsync(newUser, isPersistent: false);
    }
  }

  // THIS CALL NEVER RETRIEVES THE NEWLY CREATED USER
  ApplicationUser user = 
  this.commonDataAccess.GetCurrentUser(User.Identity.Name);

  // IRREVERENT DATA REMOVED

}

GetCurrentUser

public ApplicationUser GetCurrentUser(string userName)
{
  return context.Users.FirstOrDefault(x => x.UserName == userName);
}

Solution

  • I could not get User.Identity.Name to recognized a logged in user. So instead I created a new call to get a user by the ID and just pass the newly created ID into the call to get a user from the database that is tracked in the Entity Graph (Foreign Key Issues)

    Working Call

    public async Task<IActionResult> CheckoutStep2(CheckoutStep2ViewModel model) {
    
      ApplicationUser user = null;
      if (model.Password != null && model.PasswordConfirm != null)
      {
        user = new ApplicationUser { UserName = model.PaymentInformation.BillingEmail, Email = model.PaymentInformation.BillingEmail };
        var result = await userManager.CreateAsync(newUser, model.Password);
        if (result.Succeeded)
        {
          await signInManager.SignInAsync(newUser, isPersistent: false);
        }
      }
    
      // THIS CALL NEVER RETRIEVES THE NEWLY CREATED USER
      user = this.commonDataAccess.GetUserById(user.Id);
    
    
      ....IRREVERENT DATA REMOVED    
    }