C
C#11mo ago
Gipper

ASP.NET Identity need help getting to respective logged in user's row in AspNetUsers table

Hello all, What the title says, I need to know how to get to that row. Here's what I've tried already from the internet:
string aspNetUserId = System.Security.Principal.WindowsIdentity.GetCurrent().GetUserId(); //returns nothing (null)
string aspNetUserId = System.Security.Principal.WindowsIdentity.GetCurrent().GetUserId(); //returns nothing (null)
var userManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); //doesn't know what OwinContext is and idk how to get to it + it doesn't know how to get to ApplicationUserManager and I also don't know where (if it even exists) that class is
var userManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); //doesn't know what OwinContext is and idk how to get to it + it doesn't know how to get to ApplicationUserManager and I also don't know where (if it even exists) that class is
Help?
4 Replies
Angius
Angius11mo ago
Try going from ClaimsPrincipal? It will be injected by default into controllers and pages as User property So User.FindFirstValue(ClaimTypes.NameIdentifier) would give you the user ID In general, that .FindFirstValue() is how you would get any claim I have a number of useful extension methods to simplify it, for example
public static long? GetNumericId(this ClaimsPrincipal principal)
{
var user = principal.FindFirstValue(ClaimTypes.NameIdentifier);
var castResult = long.TryParse(user, out var userId);
return castResult ? userId : null;
}

public static string? GetUsername(this ClaimsPrincipal principal)
=> principal.FindFirstValue(ClaimTypes.Name);
public static long? GetNumericId(this ClaimsPrincipal principal)
{
var user = principal.FindFirstValue(ClaimTypes.NameIdentifier);
var castResult = long.TryParse(user, out var userId);
return castResult ? userId : null;
}

public static string? GetUsername(this ClaimsPrincipal principal)
=> principal.FindFirstValue(ClaimTypes.Name);
Gipper
GipperOP11mo ago
GetNumericId is the same it just casts into a long value, right?
Angius
Angius11mo ago
I mean, you can see what it does Identity stores the IDs as strings, by default And since I set it to use longs for sequential IDs, I need to parse that If your IDs are strings, keep it as-is If they're GUIDs, you might need to parse the strings to a GUID instead of a long Etc
Gipper
GipperOP11mo ago
thanks, it works ❤️ yeah, I just don't understand very well what claims are or how they work
Want results from more Discord servers?
Add your server