控制器构造函数中的ASP.NET Core访问User.Identity

时间:2018-06-27 19:59:45

标签: c# asp.net-core asp.net-core-mvc entity-framework-core

在我的情况下,我需要在构造器的控制器中访问User.Identity声明。

我需要这个,因为声明具有我启动自定义数据库上下文(连接字符串)所需的信息

我该如何进行访问?我只是注入DBContext,但是根据用户的不同,他们可能需要访问其他数据库。

是否有更好的方法来考虑这一点?

[Authorize]
public class DefaultController : Controller
{
    public DefaultController()
    {
        // this is NULL
        var authenticatedUser = User.Identity.Name;
    }
}

5 个答案:

答案 0 :(得分:8)

从ASP.NET Core 2.1版开始,提供了HttpContextAccessor。为此,我们必须遵循以下步骤:

使用ConfigureServices的{​​{1}}方法中的标准实现来配置服务:

Startup.cs

在控制器上执行services.AddHttpContextAccessor(); 的依赖项注入。使用IHttpContextAccessor属性访问HttpContext

User

答案 1 :(得分:1)

tab

答案 2 :(得分:0)

要访问.Net核心中的User.Identity声明,您需要使用HttpContext。这是我下面的实现

首次注册

services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();

然后在Service或Controller类中注册

private readonly IHttpContextAccessor _httpContextAccessor;

public UserService(
            IHttpContextAccessor httpContextAccessor,
            IUnitOfWork unitOfWork,
            UserManager<User> userManager,
            SignInManager<User> signInManager,
            RoleManager<ApplicationRole> roleManager)
        {
            _httpContextAccessor = httpContextAccessor;
            _unitOfWork = unitOfWork;
            _userManager = userManager;
            _signInManager = signInManager;
            _roleManager = roleManager;
            _currentUserGuid = _httpContextAccessor?.HttpContext?.User?.FindFirst(UserClaimsKey.Sub)?.Value;
            _currentUserName = _httpContextAccessor?.HttpContext?.User?.Identity?.Name;
            _currentUserEmail = _currentUserGuid == null ? "" : userManager.FindByIdAsync(_currentUserGuid)?.Result?.Email;
        }

有关实现的详细信息,请参见here

如果您有任何问题,请告诉我

答案 3 :(得分:0)

从链接上方的Rabea AlTaradeh:

    Startup.cs
     //services section
     services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

[Authorize]
public class HomeController : Controller
{
  #region DI         
  private string UserEmail;
  private readonly IHttpContextAccessor _httpContextAccessor;
  public HomeController(IHttpContextAccessor httpContextAccessor)
  {
    _httpContextAccessor = httpContextAccessor;
    UserEmail = _httpContextAccessor.HttpContext.User.Claims
                .FirstOrDefault(c => c.Type == "preferred_username")?.Value;

  }
  #endregion DI 
   public IActionResult Index()
   {            
      ViewBag.UserEmail = UserEmail;   
      return View();
   }
}

答案 4 :(得分:0)

在Asp.net Core v.2 +中,您不必注入HttpContext之类的东西。像这样访问用户:

public IActionResult GetMe()
{
    return Ok(User.Identity.Name);
}