MVC中Localhost页面重定向次数过多问题求助
MVC中Localhost出现重定向次数过多错误
错误现象
- 浏览器弹出"Too many redirects"(重定向次数过多)提示
- URL里反复出现编码后的ReturnUrl参数,陷入循环重定向
问题代码拆解
Program.cs 认证配置
builder.Services.AddAuthentication("CookieAuthentication").AddCookie("CookieAuthentication", options => { options.LoginPath = "/<Login/LoginView"; // 这里路径写错了,多了个<符号 options.AccessDeniedPath = "/Login/AccessDenied"; }); // 请求管道配置 app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Login}/{action=Signup}/{id?}"); app.Run();
登录控制器代码
[HttpPost] [ValidateAntiForgeryToken] public IActionResult LoginView(string username, string password) { if (!ModelState.IsValid) { // 错误处理代码 } if (!UserExists(username, password))// 检查用户是否在数据库中存在 { // 错误处理代码 } TempData["Username"] = username; return RedirectToAction("Index", "Home"); // 断点显示这段代码执行了,但跳转后还是出错 }
解决方法
修复LoginPath的拼写错误
把Program.cs里的options.LoginPath = "/<Login/LoginView";改成正确路径:options.LoginPath = "/Login/LoginView";错误的路径会让认证系统找不到登录页面,直接导致循环重定向。
登录成功后生成认证Cookie
原代码只存了个TempData,根本没给系统留下用户已登录的凭证,所以跳转到带[Authorize]的Home控制器时,系统还是会把用户踢回登录页。必须在验证通过后加这段代码:// 生成用户声明 var claims = new List<Claim> { new Claim(ClaimTypes.Name, username) }; // 创建身份标识 var identity = new ClaimsIdentity(claims, "CookieAuthentication"); // 创建认证主体 var principal = new ClaimsPrincipal(identity); // 登录并生成Cookie await HttpContext.SignInAsync("CookieAuthentication", principal);记得把方法改成异步:
public async Task<IActionResult> LoginView(...)给登录页面的GET方法开匿名访问权限
在Login控制器的LoginView GET方法上加上[AllowAnonymous],不然未登录用户连登录页都进不去,直接触发重定向:[HttpGet] [AllowAnonymous] public IActionResult LoginView() { return View(); }
改完这三点,登录成功后系统会生成认证Cookie,跳转到Home/Index时就能识别用户已登录,不会再循环重定向了。
内容的提问来源于stack exchange,提问作者Babar Hussain
相关产品推荐
相关产品推荐

