【发布时间】:2020-10-05 19:47:51
【问题描述】:
我目前正在使用 .NET Core,并且正在尝试获取当前用户 ID。我知道System.Web 在 NET Core 中不可用,所以我尝试使用IHttpContextAccessor。
我也将此添加到我的Startup.cs:service.AddHttpContextAccessor()
然后我尝试通过在我的控制器中执行此操作来查找用户 ID:
public Controller(IHttpContextAccessor httpContextAccessor){
var userId = httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier)
}
但它总是返回null,有谁知道为什么并且能够提供建议?我还禁用了anonymousAuthentication 并将windowsAuthentication 设置为true。
编辑
我对@987654328@ 所做的唯一更改是在ConfigureServices 方法中。
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddHttpContextAccessor();
}
【问题讨论】:
标签: asp.net asp.net-mvc authentication .net-core httpcontext