如何在asp.net core中获取当前用户
问题描述:
我想获取当前用户,以便我可以访问他们的电子邮件地址等字段.但是我不能在 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
在控制器的构造函数中几乎为空.在每个动作中都得到一个用户是不好的.我想获取一次用户的信息并保存到ViewData
;
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();
}
答
User.FindFirst(ClaimTypes.NameIdentifier).Value
编辑构造函数
以下代码有效:
public Controller(IHttpContextAccessor httpContextAccessor)
{
var userId = httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value
}
编辑 RTM
你应该注册IHttpContextAccessor
:
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();
}