ASP.NET Core生产环境RedirectToAction跳转异常:错误查找Login视图
登录失败跳转异常问题排查与解决
问题描述
在ASP.NET Core项目中,Login控制器的Post请求方法里,登录失败时调用return RedirectToAction("Index", "Login"),但生产环境下并未跳转到Login/Index视图,反而尝试加载Login/Login.cshtml,抛出以下异常:
InvalidOperationException: The view 'Login' was not found. The following locations were searched:
/Views/Login/Login.cshtml
/Views/Shared/Login.cshtml
对应的控制器代码:
[HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Login(User user) { try { user.Password = EncryptDecrypt.EncryptString(user?.Password); var result = await ecleDbService.GetUser(user, baseUrl); if (result != null && result.LoginName != null) { HttpContext.Session.SetString("LoginUser", user.LoginName); TempData["LoginUser"] = HttpContext.Session.GetString("LoginUser"); return RedirectToAction("ClientList", "Client"); } else { // need to not redirect but show login failed TempData["LoginError"] = "Login for user: " + user.LoginName + " failed."; TempData["EmailMessage"] = "For support email: myemail@myemail.com"; return RedirectToAction("Index", "Login"); } //return View("Index"); } catch(Exception ex) { string message = ex.Message; return View(); } }
原因分析
- 异常分支清getto(:/M班M X
�接力解释ms传统收到丁坝回复**:catch块中return View();未指定视图名称时,ASP.NET Core会默认寻找与当前Action同名的视图(即Login视图),但项目中仅存在Index视图,因此触发找不到视图的异常。 - 潜在执行路径问题:若登录逻辑执行过程中抛出异常,代码会直接进入catch分支,跳过else分支的正确跳转逻辑,导致错误。
解决方案
1. 修复catch分支返回逻辑
将catch块中的return View();改为明确跳转至Login/Index,或指定返回Index视图:
catch(Exception ex) { string message = ex.Message; TempData["LoginError"] = "登录过程中发生错误:" + ex.Message; // 方案1:重定向到Index动作 return RedirectToAction("Index", "Login"); // 方案2:直接返回Index视图 // return View("Index"); }
2. 验证Index动作与视图存在性
确认Login控制器中存在Index方法,且/Views/Login/Index.cshtml视图文件已创建并正确放置。
3. 确保Session配置正常
由于使用TempData传递错误信息,需确保项目已启用Session服务:
// Program.cs 配置示例 builder.Services.AddSession(); // ... app.UseSession();
总结
核心问题是异常分支的返回逻辑未指定正确视图/跳转,导致默认寻找不存在的Login视图。修复后可确保无论登录失败还是抛出异常,都能正确跳转至登录首页并显示错误信息。
内容的提问来源于stack exchange,提问作者Travis Bascom
相关产品推荐
相关产品推荐

