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

后端 未结 5 926
旧时难觅i
旧时难觅i 2021-01-03 04:15

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

5条回答
  •  攒了一身酷
    2021-01-03 05:00

    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 _userManager;
    […]
    var userID = _userManager.GetUserId(User);
    

提交回复
热议问题