_Layout.cshtml中SignInManager.IsSignedIn(User)始终返回false问题排查
问题定位与解决:登录后SignInManager.IsSignedIn(User)始终返回false
核心问题分析
你的代码存在两个关键错误,导致身份验证状态无法被正确识别:
- 中间件顺序错误:ASP.NET Core中间件执行顺序严格,
UseAuthentication()必须在UseAuthorization()之前运行,否则授权逻辑无法获取已认证的用户信息。 - 终端中间件位置错误:
app.Run()是终端中间件,执行后会直接终止请求管道,你把app.UseAuthentication()放在了它后面,导致这个身份验证中间件完全不会被执行。
修正后的Program.cs代码
using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using SampleWebApplication.Model; var builder = WebApplication.CreateBuilder(args); var connectionString = builder.Configuration.GetConnectionString("AuthConnectionString") ?? throw new InvalidOperationException(); // 注册服务 builder.Services.AddRazorPages(); builder.Services.AddControllersWithViews(); builder.Services.AddIdentity<IdentityUser, IdentityRole>() .AddEntityFrameworkStores<AuthDbContext>(); builder.Services.AddDbContext<AuthDbContext>(options => options.UseSqlServer(connectionString)); var app = builder.Build(); // 配置请求管道 if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); // 先执行身份验证中间件 app.UseAuthentication(); // 再执行授权中间件 app.UseAuthorization(); app.MapRazorPages(); // 终端中间件放在最后 app.Run();
关键修正点说明
- 调整中间件顺序:将
app.UseAuthentication()移到app.UseAuthorization()之前,确保请求先完成身份验证,再进入授权逻辑。 - 调整终端中间件位置:将
app.Run()移到所有中间件配置的最后,保证前面的中间件都能正常执行。 - 移除未使用的
Microsoft.AspNetCore.Authentication.Cookies引用,因为AddIdentity已经默认配置了Cookie认证。
确认_Layout.cshtml的正确性
你的_Layout.cshtml代码没有问题,注入SignInManager<IdentityUser>和使用SignInManager.IsSignedIn(User)的方式完全正确,修正Program.cs后即可正常识别登录状态。
内容的提问来源于stack exchange,提问作者Mariam
相关产品推荐
相关产品推荐

