如何在ASP.NET Core中获得当前用户 [英] How to get current user in asp.net core
本文介绍了如何在ASP.NET Core中获得当前用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想找一个当前用户来获取诸如电子邮件之类的用户信息. 但是我不能在asp.net核心中做到这一点.我很混乱 这是我的代码.
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
在控制器的构造函数中几乎为空.
在每个动作中都吸引用户是不好的.我想一次获取用户信息并将其设置为ViewData
;
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();
}
推荐答案
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();
}
这篇关于如何在ASP.NET Core中获得当前用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文