I want to get a current user for getting information of a user such as an email. But I can't do that in asp.net core. I'm so confused This is my code.
HttpContext
almost is null in constructor of controller.
It's not good to get a user in each action. I Wanna get information of user once and set them into ViewData
;
public DashboardController()
{
var user = HttpContext.User.GetUserId();
}
User.FindFirst(ClaimTypes.NameIdentifier).Value
EDIT for constructor
Below code works:
public Controller(IHttpContextAccessor httpContextAccessor)
{
var userId = httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value
}
Edit for RTM
You should register IHttpContextAccessor
:
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();
}