在我的LoginController中,我已经将UserManager和SignInManager注入到构造函数中,并成功地验证了一个用户:
var result = await _signInManager.PasswordSignInAsync(login.Email, login.Password, false, false);
结果。成功是真的。所有的好。我在浏览器中得到一个验证cookie。
在我的_layout。cshtml视图,我想使用SignInManager来检查我的用户是否已登录。我将适当的部分注入cshtml文件,如下所示:
@using Microsoft.AspNetCore.Identity
@inject SignInManager<ApplicationUser> signInManager
@inject UserManager<ApplicationUser> userManager
然后使用代码检查User属性是否已登录。
@if (signInManager.IsSignedIn(User))
问题:看起来用户声明主体为空或未初始化任何数据。signInManager。issigndin总是返回false,即使我有一个成功的用户认证。
我认为SignInManager应该创建我需要的所有默认声明和主体。是否还有其他原因导致主体在cshtml视图中不可用?
编辑:添加startup.cs代码
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DocumentsContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc();
services.AddControllersWithViews();
services.AddRazorPages();
services.AddInfrastructure();
// For Identity
services.AddIdentity<ApplicationUser, IdentityRole>(
options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<DocumentsContext>()
.AddDefaultTokenProviders();
services.ConfigureApplicationCookie(options => {
options.Cookie.Name = "Wdd.Identity.User";
options.ExpireTimeSpan = TimeSpan.FromMinutes(120);
options.SlidingExpiration = true;
options.LoginPath = "/Login/Login";
options.LogoutPath = "/Account/Logout";
});
// Adding Authentication
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
});
services.Configure<IdentityOptions>(options =>
{
options.Password.RequireDigit = true;
options.Password.RequiredLength = 6;
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
options.Lockout.MaxFailedAccessAttempts = 3;
});
services.Configure<MailSettings>(Configuration.GetSection("MailSettings"));
services.Configure<AppConfiguration>(Configuration.GetSection("appConfiguration"));
InitCommon();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
你的项目混合了cookie认证和Identity。
只需从Startup.cs中删除以下代码:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
});