_userManager.GetUserAsync(User) 返回 null [英] _userManager.GetUserAsync(User) returns null

查看:25
本文介绍了_userManager.GetUserAsync(User) 返回 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

基于这两个线程:

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

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

我试过了:

var 结果 = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);如果(结果.成功){ClaimsPrincipal currentUser = this.User;var thisUser = await _userManager.GetUserAsync(currentUser);如果(thisUser.EmailConfirmed){return View("~/Views/Task/Index.cshtml");}别的{返回视图(确认电子邮件");}}

还有这个:

var 结果 = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);如果(结果.成功){var thisUser = await _userManager.GetUserAsync(HttpContext.User);如果(thisUser.EmailConfirmed){return View("~/Views/Task/Index.cshtml");}别的{返回视图(确认电子邮件");}}

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

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

解决方案

你的方法有问题,MembershipIdentity 都是这样:它们是基于在 cookies 上.只有客户端发送的 Cookie 才能被读取.

所以,这是你的流程:

  1. 设置cookie
  2. 读取cookie

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

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

  1. 设置cookie
  2. 根据您已有的电子邮件从存储的任何位置读取数据

I am trying to check a users email confirmation status after login and then direct them accordigly.

Based on these two threads:

ASP.NET Core Identity - get current user

How get current user in asp.net core

I tried this:

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

And also this:

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

From inside controller but thisUser is always null.

How do I check on logon that their email is confirmed and re-direct appropriately?

解决方案

There's a problem to your approach, which is true for Membership and Identity: they're based on cookies. Cookies can only be read if they are sent by the client.

So, this is your flow:

  1. Set cookie
  2. Read cookie

This is wrong as explained above. Your flow should either be:

  1. Set cookie
  2. Redirect somewhere
  3. Read cookie (which now was sent by the client)

OR

  1. Set cookie
  2. Read data from wherever it's stored basing on the email you already have

这篇关于_userManager.GetUserAsync(User) 返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆