ASP.NET登录验证通过后无法跳转至Index页面问题咨询
ASP.NET登录验证通过后无法跳转至Index页面的解决方案
问题原因
- 认证方案不匹配:登录逻辑中使用了自定义的
"MyCookieAuth"认证方案,但IndexModel上的[Authorize]特性默认采用CookieAuthenticationDefaults.AuthenticationScheme(即"CookieAuthentication")作为授权验证方案。两者不一致导致系统无法识别已登录用户,触发授权失败重定向回登录页。 - 冗余无效代码:
OnPostAsync方法中重复创建了ClaimsIdentity和AuthenticationProperties对象,但未实际使用,属于无效代码。
解决方案
1. 统一认证与授权方案
修改login.cshtml.cs中的登录逻辑,将认证方案统一为默认的Cookie认证方案:
public async Task<IActionResult> OnPostAsync() { if (!ModelState.IsValid) return Page(); if (Credential.UserName == "admin" && Credential.Password == "password") { List<Claim> claims = new List<Claim> { new Claim(ClaimTypes.Name, "admin"), new Claim(ClaimTypes.Email, "admin@OT2.com") }; // 使用默认Cookie认证方案创建身份标识 var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(identity); // 使用默认方案执行登录 await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal); return RedirectToPage("/Index"); } return Page(); }
2. 清理冗余代码
删除原代码中未使用的ClaimsIdentity和AuthenticationProperties相关代码,避免代码混乱。
3. 确保Cookie认证服务正确配置
在项目的Program.cs(.NET 6+)中添加Cookie认证和授权服务的配置,并保证中间件顺序正确:
var builder = WebApplication.CreateBuilder(args); // 添加Razor Pages支持 builder.Services.AddRazorPages(); // 配置Cookie认证 builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.LoginPath = "/Account/Login"; // 指定授权失败时跳转的登录页路径 options.ExpireTimeSpan = TimeSpan.FromMinutes(30); // 可选:设置Cookie有效期 }); // 添加授权服务 builder.Services.AddAuthorization(); var app = builder.Build(); // 中间件顺序:先认证,再授权 app.UseAuthentication(); app.UseAuthorization(); app.MapRazorPages(); app.Run();
完成以上修改后,登录验证通过后即可正常跳转至Index页面。
内容的提问来源于stack exchange,提问作者Manatchanok Bumrungban
相关产品推荐
相关产品推荐

