.net核心中的Cookie身份验证中的User.identity.name为null

时间:2019-03-12 19:03:17

标签: asp.net-core authorization cookie-authentication

我在.Net Core中使用cookie身份验证和授权。我的问题是在SignInAsync之后,我得到了User.identity.name为null,并且还声称计数为0。
这是我的控制器代码

     ClaimsIdentity identity = new ClaimsIdentity(new[] {
                        new Claim(ClaimTypes.Name, "Hunzla-1"),
                        new Claim(ClaimTypes.Role, "Admin")
                    }, CookieAuthenticationDefaults.AuthenticationScheme);  
 var principal = new ClaimsPrincipal(identity);
 var login = HttpContext.SignInAsync(principal);
 string s=User.Identity.Name;  //s is empty

我的Startup.cs代码

 public void ConfigureServices(IServiceCollection services)
            {
                services.Configure<CookiePolicyOptions>(options =>
                {  options.CheckConsentNeeded = context => true;
                    options.MinimumSameSitePolicy = SameSiteMode.None;
                });
                services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

                services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(o => o.LoginPath = new PathString("/account/login"));
                      }
    }
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                    app.UseHsts();
                }

                app.UseHttpsRedirection();
                app.UseStaticFiles();
                app.UseCookiePolicy();
                app.UseAuthentication();
                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });
            }

0 个答案:

没有答案