调用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>");
答案 0 :(得分:0)
问题似乎是您正在尝试使用user
对象进行播放。您应该获得对创建的用户的 true 引用。
检查用户是否已成功创建后,您可以执行以下操作:
if(result.succeeded)
{
var theNewUser = await UserManager.FindByEmailAsync(model.Email);
//Do other things with the new user.
}
答案 1 :(得分:0)
我在发送电子邮件的功能中收到错误,似乎此错误正在影响会话,并且用户已重定向到登录页面。而且这是在开发模式下发生的,因为电子邮件问题仅出现在生产环境中。感谢bolkay的帮助。