【问题标题】:Identity Framework Add User and use in same method身份框架添加用户并以相同的方法使用
【发布时间】:2017-06-13 00:13:32
【问题描述】:

我有一个电话,如果他们在购买产品时输入密码,就会创建一个新用户。如果他们创建了一个帐户,那么我必须更新要反映给该用户的数据。但我遇到的问题是我无法在同一次通话中使用该用户,并且无法弄清楚如何更新身份框架以识别新创建的用户。如果页面被刷新并再次尝试它可以工作,但第一次它会产生错误......因为没有用户。

它将数据保存在 AspNetUsers 表中。 newUser 对象有一个分配的用户。但我也无法使用该对象。我尝试将 newUser 对象拉出并分配 newUser 对象,但它随后尝试创建具有相同 ID 的新用户,但出现外键错误。我不知道怎么做,所以我可以在同一个调用中使用新创建的用户。

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

}

获取当前用户

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

【问题讨论】:

  • 您要为用户获取哪些数据,而您在ApplicationUser 对象中还没有?
  • 所有数据都在那里...但是当我将用户分配到一个新对象上时,它会将其作为新添加进行跟踪并尝试再次添加它,但我遇到了外键错误。所以我不得不返回并再次从数据库中获取 ApplicationUser,以便 Entity 正确跟踪它。

标签: asp.net asp.net-mvc asp.net-core asp.net-core-mvc asp.net-identity


【解决方案1】:

我无法让 User.Identity.Name 识别登录用户。因此,我创建了一个新调用来通过 ID 获取用户,并将新创建的 ID 传递到调用中以从实体图中跟踪的数据库中获取用户(外键问题)

工作电话

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    
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-26
    • 1970-01-01
    • 2011-04-29
    • 2015-12-19
    • 1970-01-01
    • 2021-12-05
    • 2021-06-29
    • 1970-01-01
    相关资源
    最近更新 更多