Categories
ASP.Net Core

Getting logged in user ID in non-controller class in ASP.Net Core

It’s easy to retrieve the current logged-in user’s information, such as user ID, username, or email, in an ASP.Net Core controller class. However, it can be tricky to access this information in other classes, like the IdentityDbContext class. Here’s an example of how to extract the current user in a non-controller class, specifically in the IdentityDbContext class:

var httpContextAccessor = this.GetService<IHttpContextAccessor>();
var userId = httpContextAccessor.HttpContext?.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;

This example demonstrates how to retrieve the user ID. Hopefully, you find it helpful.

Happy coding 🙂