用户管理器创建函数调用后的问题



调用UserManager.Create方法后遇到问题。问题是当前登录的用户在创建新用户后丢失了凭据。我会把我的代码放在这里

public async Task<ActionResult> CrearUser(CreateUserModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser
{
FirstName = model.FirstName,
LastName = model.LastName,
UserName = model.UserName,
Email = model.Email,
PhoneNumber = model.PhoneNumber,
ActiveSince = Convert.ToDateTime(model.ActiveSince),
ActiveUntil = Convert.ToDateTime(model.ActiveUntil)
};
var result =  UserManager.Create(user, model.Password);
if (result.Succeeded)
{

// For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
string code = HttpUtility.UrlEncode(await UserManager.GenerateEmailConfirmationTokenAsync(user.Id));
var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href="" + callbackUrl + "">here</a>");

var roleStore = new RoleStore<IdentityRole>();
var roleMngr = new RoleManager<IdentityRole>(roleStore);
string name = roleMngr.FindById(model.rolid).Name;
await this.UserManager.AddToRoleAsync(user.Id, name);
Success(string.Format(" Usuario <b>{0}</b> Creado con Exito.", model.UserName), true);
return RedirectToAction("Index");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
model.Roles = GetRoles();
return View(model);
}

删除代码以发送确认邮件我没有问题。有谁知道什么会影响那里?

string code = HttpUtility.UrlEncode(await UserManager.GenerateEmailConfirmationTokenAsync(user.Id));
var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href="" + callbackUrl + "">here</a>");

问题似乎是您正在尝试使用user对象。您应该改为获得对创建用户的真实引用。

检查用户是否已成功创建后,您可以执行以下操作:

if(result.succeeded)
{
var theNewUser = await UserManager.FindByEmailAsync(model.Email);
//Do other things with the new user.
}

我在发送电子邮件的函数中收到错误,似乎此错误影响了会话,用户被重定向到登录页面。它发生在开发模式下,因为电子邮件问题只存在于生产环境中。感谢博尔凯的帮助。

最新更新