Asp.net core HttpContext.User.Claims和IHttpContextAccessor在成功登录后都返回空值

Asp.net core HttpContext.User.Claims和IHttpContextAccessor在成功登录后都返回空值,asp.net-core,.net-core,asp.net-identity,claims-based-identity,Asp.net Core,.net Core,Asp.net Identity,Claims Based Identity,HttpContext.User.Claims和IHttpContextAccessor在成功登录.NET Core 2.2后都返回空值 这里是我的创业服务 services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")

HttpContext.User.Claims和IHttpContextAccessor在成功登录.NET Core 2.2后都返回空值 这里是我的创业服务

  services.AddDbContext<ApplicationDbContext>(options =>
              options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")
                     ,b=>b.MigrationsAssembly("AdaptiveBizapp")));

            services.AddDbContext<Project_Cost_Management_SystemContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("Project_Cost_Management_SystemContext") 
                    , b => b.MigrationsAssembly("AdaptiveBizapp")));

            services.AddDefaultIdentity<ApplicationUser>()
                .AddRoles<ApplicationRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                 .AddDefaultTokenProviders();

            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => false;
                options.MinimumSameSitePolicy = SameSiteMode.None;

            });
            services.ConfigureApplicationCookie(options => {
                options.LoginPath = "/Account/login";
                options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;                
                });
            services.AddDistributedMemoryCache();

            services.AddSession(options =>
            {
                // Set a short timeout for easy testing.
                options.IdleTimeout = TimeSpan.FromMinutes(30);
                options.Cookie.HttpOnly = true;
                // Make the session cookie essential
                options.Cookie.IsEssential = true;
            });
 services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); 

我使用了基于身份和角色的授权。登录成功后,在HomeController中读取用户声明或NameIdentifier为空时。但当我在同一个LoginController中阅读时,它在ClaimPrincipal中有价值

  public async override Task<ClaimsPrincipal> CreateAsync(ApplicationUser user)
        {
            var principal =await base.CreateAsync(user);

            // Add your claims here
            ((ClaimsIdentity)principal.Identity).
               AddClaims(new[] {
         new System.Security.Claims.Claim(ClaimTypes.NameIdentifier,
            user.UserName.ToString()) 
            });


            return principal;
        }
public async override Task CreateAsync(ApplicationUser用户)
{
var principal=await base.CreateAsync(用户);
//在此处添加您的索赔
((索赔实体)委托人身份)。
AddClaims(新[]{
新系统.Security.Claims.Claim(ClaimTypes.NameIdentifier,
user.UserName.ToString())
});
返还本金;
}


如果要对IHttpContextAccessor使用依赖注入,则需要添加:

public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
        ...
        services.AddHttpContextAccessor();
        services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        ...
        }
    }
public void配置服务(IServiceCollection服务)
{
配置(选项=>
{
...
AddHttpContextAccessor();
services.TryAddSingleton();
...
}
}

搜索了一整天,终于找到了答案。在下一次呼叫服务器时,这些声明会被水合。希望这篇文章能帮助其他人。如果你遵循微软的文档,你很好,但不要试图在设置声明的同一次呼叫中获得声明。再打一次电话,它们就会被水合。

你确定厨师会这么做吗ie设置正确,并且您的浏览器出于某种原因未阻止cookie?如果未设置cookie,则不会在后续请求中提交cookie,并且用户不会被视为未登录,正如您在第一个屏幕截图中看到的
IsAuthenticated=false
i拥有451个登录用户角色。是否对声明大小有任何限制?我的浏览器没有阻止cookie。我有上面的代码。目前正在将MVC5迁移到Core 2.2,但如果您在浏览器中,是否设置了cookie?不确定声明是否存储在cookie中(它们不应该,但不依赖它).Cookie大小限制对于大多数应用程序/浏览器来说大约是4kb。我在上面附加了我的浏览器Cookie。我在服务配置中启用Cookie集(见顶部)。我担心服务的顺序包括。Cookie创建为applicationc1到ApplicationC9@Tsenggreat!。我错过了服务。AddHttpContextAccessor();在我的代码中输入一行。在这之后它就可以工作了。再次感谢。
public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
        ...
        services.AddHttpContextAccessor();
        services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        ...
        }
    }