Frip
Frip

Reputation: 884

How to get current user id, if i inherits from IdentityUser?

I add some fields in IdentityUser like a

public class CustomUser: IdentityUser
    {
        public string field1 {get;set;}
        public string field2 {get;set;}
    }

after migration, on Sql Management studio i had all data, which i added with .OnModelCreating

But, How i can get any field from current authorized CustomUser (like a ID)

I try use

using Microsoft.AspNet.Identity;

CustomUser.Identity.GetUserId()

But it doesnt work.

Thanks for help!

Upvotes: 7

Views: 11308

Answers (3)

Hafizur Rahman
Hafizur Rahman

Reputation: 1

Display current application user name in view:

@User.Identity?.Name`

Display current Windows user name in view:

@Environment.UserName

Upvotes: 0

Xueli Chen
Xueli Chen

Reputation: 12685

In ASP.Net Core ,if your Controller inherits the Microsoft.AspNetCore.Mvc.Controller, you could get the IClaimsPrincipal from the User property and get the actual "Id" of the user,

using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;

ClaimsPrincipal currentUser = this.User;
var currentUserID = currentUser.FindFirst(ClaimTypes.NameIdentifier).Value;

You can also get the data of all fields(include Id) from the database's User entity:

1.DI UserManager

    private readonly UserManager<ApplicationUser> _userManager;

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

2.Use it like below:

var id = userManager.GetUserId(User); // get user Id
var user = await userManager.GetUserAsync(User); // get user's all data

Upvotes: 12

Hammad Shabbir
Hammad Shabbir

Reputation: 731

You need to first save user data in claims and then get authorized user data.

Add Claims

var identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()));

Get Claims

var userId = (HttpContext.Current.User.Identity as ClaimsIdentity).Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier)

Upvotes: 2

Related Questions