_userManager.GetUserAsync(用户)returns 空

_userManager.GetUserAsync(User) returns null

我正在尝试在登录后检查用户的电子邮件确认状态,然后相应地指导他们。

基于这两个线程:

我试过这个:

var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
    ClaimsPrincipal currentUser = this.User;
    var thisUser = await _userManager.GetUserAsync(currentUser);
    if(thisUser.EmailConfirmed)
    {
        return View("~/Views/Task/Index.cshtml");
    }
    else
    {
        return View("ConfirmEmail");
    }
}

还有这个:

var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{   
    var thisUser = await _userManager.GetUserAsync(HttpContext.User);
    if(thisUser.EmailConfirmed)
    {
        return View("~/Views/Task/Index.cshtml");
    }
    else
    {
        return View("ConfirmEmail");
    }
}

来自控制器内部,但 thisUser 始终为空。

如何在登录时检查他们的电子邮件是否已确认并正确重定向?

您的方法存在问题,MembershipIdentity 也是如此:它们基于 cookies。 Cookie 只有在客户端发送时才能被读取。

所以,这是你的流程:

  1. 设置 cookie
  2. 读取 cookie

如上所述,这是错误的。您的流程应该是:

  1. 设置 cookie
  2. 重定向到某处
  3. 读取cookie(现在由客户端发送)

  1. 设置 cookie
  2. 根据您已有的 email
  3. 从存储的任何位置读取数据

我在模型中有电子邮件,所以我直接在数据库中查找它。

var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
    _logger.LogInformation("User logged in.");

    var user = _context.Users.Single(x => x.Email == model.Email);

    if(user.EmailConfirmed)
    {
        return View("~/Views/Task/Index.cshtml");
    }
    else
    {
        return View("ConfirmEmail");
    }

}

来自docs

Identity is enabled by calling UseAuthentication. UseAuthentication adds authentication middleware to the request pipeline.

因此,在 Configure 方法中,如果您忘记设置

app.UseAuthentication();

你会得到相同的结果,没有任何错误。