MVC 5 ASP.NET身份 - CreateSync无效的用户ID



我有两个使用一个数据库的网站,我使用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>.");
}

发生的事情是,当用户注册时,他在将用户ID设置为3d847c51-7217-49fe-ae9d-d8e46e291559时收到的URL,但是在数据库中,用户是使用95789d6e-b66e-4c9e-8ee4-fe384b82e838创建的。我不明白这会如何发生。顺便说一下,数据库中没有ID 3d847c51-7217-49fe-ae9d-d8e46e291559的用户。您是否知道为什么以及如何发生这种情况?

我建议在Create成功后通过标识符回电以确保属性匹配。

//...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);

//...删除的其他代码

我也怀疑问题与UserManager.CreateAsync()方法有关。您正在正确使用。我宁愿使用手动生成的用户ID,而不是由UserManager生成。

在您的情况下将是:

    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");
    } 

相关内容

  • 没有找到相关文章

最新更新