如何在asp.net core中获取当前用户 [英] How to get current user in asp.net core

查看:72
本文介绍了如何在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();
    }

这篇关于如何在asp.net core中获取当前用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆