How to get current user in asp.net core

Mehran Hafizi picture Mehran Hafizi · Apr 15, 2016 · Viewed 190.8k times · Source

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();
}

Answer

adem caglin picture adem caglin · Apr 15, 2016
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();
    }