Mehran Hafizi Mehran Hafizi - 3 months ago 69
ASP.NET (C#) Question

How get current user in asp.net core

I want to get current user for geting information of user such as email.
But i cant do that in asp.net core.I'm so cunfused
This is my code.

HttpContext almost is null in constructor of controller.
It's not good get user in each action.I Wanna get information of user once and set them into ViewData;

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

Answer
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.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    }