【问题标题】:_userManager.GetUserAsync(User) returns null_userManager.GetUserAsync(User) 返回 null
【发布时间】:2018-02-18 12:49:57
【问题描述】:

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

基于这两个线程:

ASP.NET Core Identity - get current user

How get current user in 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 始终为空。

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

【问题讨论】:

    标签: c# asp.net-core asp.net-core-mvc asp.net-core-2.0


    【解决方案1】:

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

    所以,这就是你的流程:

    1. 设置cookie
    2. 读取 cookie

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

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

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

        来自docs

        通过调用UseAuthentication 启用身份。使用身份验证 将身份验证middleware 添加到请求管道。

        所以,在Configure 方法中,如果你忘记设置了

        app.UseAuthentication();
        

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

        【讨论】:

          猜你喜欢
          • 2016-05-11
          • 2021-07-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-02-04
          • 2017-03-17
          • 1970-01-01
          • 2021-11-26
          相关资源
          最近更新 更多