首页 文章

如何在.NET Core 2.0中获取登录用户的用户ID?

提问于
浏览
4

我使用.NET Core和MVC创建了一个angular 2应用程序 . 我想知道用户的登录ID . 如何在.net核心中登录用户的ID?

这是我的第一个角度应用程序 . 我使用以下链接开始https://blogs.msdn.microsoft.com/webdev/2017/02/14/building-single-page-applications-on-asp-net-core-with-javascriptservices/

我想使用Windows身份验证,以获取控制器中的登录ID .

5 回答

  • 14

    假设您正在使用ASP.NET Identity,那么(在您的控制器操作中):

    User.Identity.GetUserId();
    

    或(如果您使用自定义键类型)

    User.Identity.GetUserId<TKey>();
    
  • 2

    试试这个:

    var user = await userManager.GetUserAsync(HttpContext.User);
    var ID = user.Id;
    
  • 2

    这实际上取决于您在应用中使用的身份验证类型 .

    考虑到你提到了Angular,我不确定你使用什么框架进行身份验证,以及你的设置是什么 .

    为了让您朝着正确的方向前进,您的行动方针将是从用户身份获得相关声明 . 像这样的东西:

    var ident = User.Identity as ClaimsIdentity;
    var userID = ident.Claims.FirstOrDefault(c => c.Type == idClaimType)?.Value;
    

    其中 idClaimType 是存储您的标识的声明的类型 . 根据框架,它通常是
    ClaimTypes.NameIdentifier= "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"
    要么
    JwtClaimTypes.Subject= "sub"

    如果您使用的是Asp.Net核心标识,则可以在 UserManager 上使用其辅助方法来简化对它的访问:

    UserManager<ApplicationUser> _userManager;
    […]
    var userID = _userManager.GetUserId(User);
    
  • 1
    private readonly ApplicationDbContext _dbContext;
    private readonly IHttpContextAccessor _httpContext;
    private readonly string _userId;
    
    public MyController(UserManager<ApplicationUser> _userManager, IHttpContextAccessor _httpContext)
    {
        this._userManager = _userManager;
        this._httpContext = _httpContext;
    
        _userId = this._userManager.GetUserId(this._httpContext.HttpContext.User);
    }
    
  • 3

    我用这个:

    private UserManager<ApplicationUser> _userManager;
    
        public ClassConstructor(UserManager<ApplicationUser> userManager)
        {
            _userManager = userManager;
        }
    
        public void OnGet()
        {
            var id = _userManager.GetUserId(User);
        }
    

    附:你可以在UserManager中找到更多有用的方法 .

相关问题