ASP.NET Core 2.2注册后自动登录跳转后点击按钮即登出的解决方法
注册后自动登录跳转后点击按钮登出的问题解决
我正在开发ASP.NET Core 2.2项目,用户首次注册后会被重定向至需登录权限的个人页面。当前代码逻辑是用户完成注册后自动登录,然后前端跳转至https://localhost:5001/UserPanel/UserInfo/Index。用户成功跳转并看到页面,但点击任意按钮后就会登出。
相关代码
login.cshtml 中的脚本
<script> $('#btnregister').on('click', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: '@Url.Action("Register", "Account")', data: { username: $("#username").val(), pass: $('#pass').val() } }).done(function (res) { if (res.status === 'success') { window.location.href = 'https://localhost:5001/UserPanel/UserInfo/Index'; }); }); </script>
AccountController 中的代码
[HttpPost] public async Task<IActionResult> Register(string username, string pass) { var user = new ApplicationUsers { PasswordHash = pass, UserName = username, }; // 注册用户 IdentityResult registerResult = await _userManager.CreateAsync(user, pass); if (registerResult.Succeeded) { registerResult = await _userManager.AddToRoleAsync(user, "normaluser"); } // 自动登录 var result = await _signInManager.PasswordSignInAsync(username, pass , true, lockoutOnFailure: false); if (result.Succeeded) { return Json(new { status = "success" }); } }
UserInfo 控制器代码
[Area("UserPanel")] [Authorize(Roles = "normaluser")] public class UserInfoController : Controller { private readonly UserManager<ApplicationUsers> _userManager; public UserInfoController(UserManager<ApplicationUsers> userManager) { _userManager = userManager; } public IActionResult Index() { ViewBag.getuser = _userManager.GetUserName(HttpContext.User); return View(); } }
问题原因及解决步骤
1. 修正用户实体的密码赋值错误
手动给ApplicationUsers的PasswordHash赋值是错误的,UserManager.CreateAsync方法会自动生成正确的密码哈希,手动赋值会导致哈希值不匹配,后续会话验证失败。
修改用户创建代码:
var user = new ApplicationUsers { UserName = username, // 移除 PasswordHash = pass 的手动赋值 };
2. 完善角色添加的错误处理
当前代码未验证角色添加是否成功,若角色添加失败,用户权限不足会触发后续操作登出。补充验证逻辑:
if (registerResult.Succeeded) { var roleResult = await _userManager.AddToRoleAsync(user, "normaluser"); if (!roleResult.Succeeded) { return Json(new { status = "error", message = "添加用户角色失败" }); } } else { var errorMsg = string.Join(",", registerResult.Errors.Select(e => e.Description)); return Json(new { status = "error", message = $"注册失败:{errorMsg}" }); }
3. 确保登录会话的有效性
检查Startup.cs中的身份认证配置,保证Cookie配置正确,避免跨路径会话丢失:
// 在 ConfigureServices 中添加 services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.LoginPath = "/Account/Login"; options.AccessDeniedPath = "/Account/AccessDenied"; options.Cookie.Path = "/"; // 确保Cookie覆盖全站路径 options.ExpireTimeSpan = TimeSpan.FromDays(7); // 合理设置Cookie有效期 }); // 在 Configure 中确保顺序正确 app.UseAuthentication(); app.UseMvc();
4. 前端跳转改用相对路径
硬编码绝对路径可能导致上下文不一致,改用Url.Action生成正确地址:
window.location.href = '@Url.Action("Index", "UserInfo", new { area = "UserPanel" })';
5. 完善控制器返回逻辑
当前Register方法在登录失败时无返回值,会导致500错误,补充分支返回:
if (result.Succeeded) { return Json(new { status = "success" }); } return Json(new { status = "error", message = "自动登录失败" });
内容的提问来源于stack exchange,提问作者topcool
相关产品推荐
相关产品推荐

