我有两个网站使用一个数据库,我使用asp.net身份(2.2.1.40403),我有一个我无法理解的问题。现在,这是第三次发生这种情况,我不知道问题出在哪里。
我有一个注册并发送这样的电子邮件方法
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new User { UserName = model.Email, Email = model.Email, RegisterDate = DateTime.Now };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
//await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
await SendConfirmationEmail(user);
return View("ConfirmationEmailSent");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
private async Task SendConfirmationEmail(Dal.Models.User user)
{
// Send an email with this link
string code = 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, "Potvrzení Vašeho účtu", "Prosím potvrďte svou emailovou adresu kliknutím <a href=\"" + callbackUrl + "\">zde</a>.");
}
当用户注册时,当userId设置为3d847c51-7217-49fe-ae9d-d8e46e291559
时,他收到了URL,但在数据库中,用户95789d6e-b66e-4c9e-8ee4-fe384b82e838
创建了用户。我不明白这是怎么发生的。顺便说一句,数据库中没有ID为3d847c51-7217-49fe-ae9d-d8e46e291559
的用户。你知道为什么以及如何发生这种情况吗?
答案 0 :(得分:1)
我建议在创建成功后通过标识符回调用户,以确保属性匹配。
//...other code removed for brevity
var user = new User { UserName = model.Email, Email = model.Email, RegisterDate = DateTime.Now };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
//pick one
//user = await UserManager.FindById(user.Id);
//user = await UserManager.FindByName(user.UserName);
user = await UserManager.FindByEmailAsync(user.Email);
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
await SendConfirmationEmail(user);
return View("ConfirmationEmailSent");
}
AddErrors(result);
// ...为简洁起见删除了其他代码
答案 1 :(得分:0)
我也怀疑该问题与UserManager.CreateAsync()
方法有关。你正确使用。我宁愿使用由UserManager
生成的手动生成的用户ID。
在你的情况下将是:
var user = new User { UserName = model.Email, Email = model.Email, RegisterDate = DateTime.Now };
user.Id = Guid.NewGuid().ToString();
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SendConfirmationEmail(user);
return View("ConfirmationEmailSent");
}