ASP.NET Core MVC中不依赖ASP.NET Core Identity实现Cookie认证的问题排查求助
我帮你排查了代码里的几个关键问题,这些应该是导致登录功能无法正常工作的核心原因:
1. 表单提交路径错误
你的登录视图中,表单的asp-action指向了Index,但实际处理登录请求的是LoginController的Login POST方法,这会导致请求找不到正确的处理逻辑:
修改后的View代码:
@model Cookie2.Model.db_user @{ ViewBag.Title = "title"; Layout = "_Layout"; } <h2>Login</h2> <!-- 修正asp-action为Login --> <form asp-action="Login" asp-controller="Login" method="post"> <label asp-for="UserName"> <input asp-for="UserName"> </label> <br /> <label asp-for="UserPassword"> <input asp-for="UserPassword"> </label> <br> <!-- 添加错误提示显示 --> @if(ViewData["ErrorMessage"] != null) { <div class="text-danger mb-2">@ViewData["ErrorMessage"]</div> } <button type="submit">Submit</button> </form>
2. 登录验证逻辑错误
你当前的用户名密码判断使用了&&,这会导致只有当用户名和密码同时错误时才会返回提示,而单一错误的情况会绕过验证逻辑,这不符合预期:
修改后的Controller验证逻辑:
// 把&&改为||,只要用户名或密码错误就返回提示 if (_User.UserName != "123" || _User.UserPassword != "123") { ViewData["ErrorMessage"] = "error!!"; return View(); }
3. 异步登录方法未等待完成
HttpContext.SignInAsync是异步方法,但你的Login方法是同步的ActionResult,这会导致Cookie还未写入就返回响应,最终登录状态没有生效:
修改为异步的Login方法:
[HttpPost] [ValidateAntiForgeryToken] // 改为async Task<IActionResult> public async Task<IActionResult> Login(db_user _User) { if (ModelState.IsValid) { if (_User.UserName != "123" || _User.UserPassword != "123") { ViewData["ErrorMessage"] = "error!!"; return View(); } var claims = new List<Claim> { new Claim(ClaimTypes.Name, _User.UserName), }; var claimsIdentity = new ClaimsIdentity( claims, CookieAuthenticationDefaults.AuthenticationScheme); var authProperties = new AuthenticationProperties { // 可选:设置Cookie持久化和过期时间 IsPersistent = true, ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(30) }; // 等待异步登录操作完成 await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties); // 建议跳转到首页,而非直接返回Content return RedirectToAction("Index", "Home"); } return View(); }
4. Startup中登录路径配置错误
你在Cookie认证配置里的LoginPath指向了/Home/Login,但实际登录页面在LoginController的Login方法,这会导致未授权请求跳转时找不到正确的登录页:
修改后的Startup配置:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.AccessDeniedPath = "/Home/AccessDeny"; // 修正为正确的登录路径 options.LoginPath = "/Login/Login"; });
完成以上修改后,再测试登录功能应该就能正常工作了。如果需要保护某个控制器或Action,只需要添加[Authorize]特性即可。
内容的提问来源于stack exchange,提问作者GG6565
相关产品推荐
相关产品推荐

