_userManager.GetUserAsync(User) 返回空值。

4
我正在尝试在登录后检查用户的电子邮件确认状态,然后根据情况引导他们。
基于这两个线程: 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始终为空。

如何在登录时检查其电子邮件已确认并适当重定向?

3个回答

4
你的方案存在问题,这对于 MembershipIdentity 都是正确的:它们都基于 cookies。只有在客户端发送cookie时才能读取cookie。
所以你的流程如下:
  1. 设置cookie
  2. 读取cookie
如上所述,这是错误的。你的流程应该是:
  1. 设置cookie
  2. 重定向到其他页面
  3. 读取cookie(此时客户端已经发送了cookie)
或者是:
  1. 设置cookie
  2. 通过已有的 email 读取存储在哪里的数据

0

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

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

}

0

来自文档

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

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

app.UseAuthentication();

你将获得相同的结果,没有任何错误。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接