tayebe pourmand
tayebe pourmand

Reputation: 195

How to get/load an existing user in ASP.NET Core Identity

I have created a user in ASP.NET Core Identity. Now I want to be able to load it.

I know I have userManager.GetUserAsync that takes a principal. But I want to be able to load it using different parameters. For example Id and Email and Username.

I want this method. var user = userManager.GetUser(userId);

How can I do that?

Upvotes: 2

Views: 190

Answers (1)

Brando Zhang
Brando Zhang

Reputation: 27962

As far as I know, the usermanager has build method which could get the username according to identity user's property.

More details about how to read the user according to identity user property, you could refer to below codes:

    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public readonly UserManager<IdentityUser> _userManager;

        public HomeController(ILogger<HomeController> logger, UserManager<IdentityUser> userManager)
        {
            _userManager = userManager;

            _logger = logger;
        }


        public IActionResult Index()
        {
            //read by Email
            var user = _userManager.Users.FirstOrDefault(x => x.Email == "[email protected]");
            //read by ID
            var user2 = _userManager.Users.FirstOrDefault(x => x.Id == "xxxxx");
            //read by username
            var user3 = _userManager.Users.FirstOrDefault(x => x.UserName == "xxxxx");

            return View();
        }
   }

Result:

enter image description here

Upvotes: 2

Related Questions