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

How to get current user in asp.net core


I want to get the current user, so I can access fields like their email address. But I can't do that in asp.net core. This is my code:

HttpContext almost is null in constructor of controller. It's not good to get a user in each action. I want to get the user's information once and save it to ViewData;

public DashboardController()
{
    var user = HttpContext.User.GetUserId();
}

Solution

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