Search code examples
c#asp.net-core-identity

Is User.FindFirstValue(ClaimTypes.NameIdentifier) getting data from the database?


If I do this, to find the ID of the logged in user:

Guid uId = Guid.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier));

Does the database get queried via UserManager, or does the information reside somewhere else? In a cookie?

Some times, I want to load related data on the ApplicationUser, and I don't want to take two trips to the database. I'm not sure if this counts as two trips:

Guid uId = Guid.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier));
ApplicationUser user = await db.Users
    .Include(c => c.City)
    .Where(u => u.Id == uId).FirstOrDefaultAsync();

I'm pretty sure this counts as two:

var usr = await _userManager.GetUserAsync(User);
ApplicationUser user = await db.Users
    .Include(c => c.City)
    .Where(u => u.Id == usr.Id).FirstOrDefaultAsync();

Solution

  • User.FindFirstValue works with current HttpContext (see User property) and has nothing to do with a database.
    Instead, it works with current HTTP request and cookies.