我想要一個(gè)當(dāng)前用戶來獲取用戶信息,例如電子郵件。但是我不能在asp.net核心中做到這一點(diǎn)。我很困惑這是我的代碼。HttpContext在控制器的構(gòu)造函數(shù)中幾乎為null 。在每個(gè)動作中都吸引用戶是不好的。我想一次獲取用戶信息并設(shè)置為ViewData;public DashboardController(){ var user = HttpContext.User.GetUserId();}
3 回答

泛舟湖上清波郎朗
TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超3個(gè)贊
User.FindFirst(ClaimTypes.NameIdentifier).Value
編輯構(gòu)造函數(shù)
下面的代碼有效:
public Controller(IHttpContextAccessor httpContextAccessor)
{
var userId = httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value
}
編輯RTM
您應(yīng)該注冊IHttpContextAccessor:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
- 3 回答
- 0 關(guān)注
- 2106 瀏覽
添加回答
舉報(bào)
0/150
提交
取消