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

泛舟湖上清波郎朗
TA貢獻1818條經驗 獲得超3個贊
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.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
- 3 回答
- 0 關注
- 2112 瀏覽
添加回答
舉報
0/150
提交
取消