繁体   English   中英

_userManager.GetUserAsync(User) 返回 null

[英]_userManager.GetUserAsync(User) returns null

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

基于这两个线程:

ASP.NET Core Identity - 获取当前用户

如何在asp.net core中获取当前用户

我试过这个:

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. 设置饼干
  2. 读取cookie

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

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

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

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

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

}

文档

通过调用UseAuthentication启用身份。 UseAuthentication 向请求管道添加身份验证中间件

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

app.UseAuthentication();

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM