Mehran Hafizi Mehran Hafizi - 7 months ago 185
ASP.NET (C#) Question

How get current user in core

I want to get current user for geting information of user such as email.
But i cant do that in 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();


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