How to get user id of logged in user in .NET Core

2020-02-29 01:56发布

I have created a angular 2 application using .NET Core and MVC. I want to know the login id of user. How to get logged in id of a user in .net core?

This is my first angular application. I used following link to start https://blogs.msdn.microsoft.com/webdev/2017/02/14/building-single-page-applications-on-asp-net-core-with-javascriptservices/

I want to use windows authentication, to get login id in a controller.

5条回答
冷血范
2楼-- · 2020-02-29 02:34
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楼-- · 2020-02-29 02:38

That really depends on what kind of authentication you have in your app.

Considering you mentioned Angular, I'm not sure what framework you use for authentication, and what are your settings.

To get you moving into the right direction, your course of action would be getting the relevant claim from the user identity. Something like this:

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

where idClaimType is the type of the claim that stores your Identity. Depending on the framework, it would usually either be
ClaimTypes.NameIdentifier (= "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier")
or
JwtClaimTypes.Subject (= "sub")

If you're using Asp.Net Core Identity, you could use their helper method on the UserManager to simplify access to it:

UserManager<ApplicationUser> _userManager;
[…]
var userID = _userManager.GetUserId(User);
查看更多
看我几分像从前
4楼-- · 2020-02-29 02:43

Try this one:

var user = await userManager.GetUserAsync(HttpContext.User);
var ID = user.Id;
查看更多
淡お忘
5楼-- · 2020-02-29 02:43

I use this one :

    private UserManager<ApplicationUser> _userManager;

    public ClassConstructor(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }

    public void OnGet()
    {
        var id = _userManager.GetUserId(User);
    }

p.s. u can find more useful method inside UserManager.

查看更多
在下西门庆
6楼-- · 2020-02-29 02:47

Assuming you are using ASP.NET Identity, what about (in your controller action):

User.Identity.GetUserId();

or (if you use a custom key type)

User.Identity.GetUserId<TKey>();
查看更多
登录 后发表回答