.NET Core 5中如何捕获浏览器关闭事件并实现用户登出
实现Asp.Net Core 5中浏览器关闭时自动登出并记录登出时间
核心逻辑
浏览器关闭事件无法直接由后端捕获,需要通过前端触发通知后端执行登出逻辑,同时配合后端会话超时兜底机制,避免前端事件未触发导致的用户状态不一致。
具体实现步骤
1. 前端监听浏览器关闭事件
在全局页面脚本中监听beforeunload事件,使用navigator.sendBeacon发送登出请求——这个API不受页面卸载的异步限制,可靠性更高。
示例前端代码:
window.addEventListener('beforeunload', () => { // 向后端发送登出请求 navigator.sendBeacon('/Account/LogoutOnClose', JSON.stringify({})); });
2. 后端编写登出接口
在Account控制器中添加授权接口,执行登出操作并将登出时间写入数据库。
示例后端C#代码:
[HttpPost] [Authorize] public async Task<IActionResult> LogoutOnClose() { var userId = User.FindFirstValue(ClaimTypes.NameIdentifier); if (!string.IsNullOrEmpty(userId)) { // 更新数据库中的用户登出时间 var user = await _userManager.FindByIdAsync(userId); if (user != null) { user.LastLogoutTime = DateTime.Now; await _userManager.UpdateAsync(user); } // 执行登出操作 await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); } return Ok(); }
3. 配置会话超时兜底
针对前端事件失败的场景(如浏览器崩溃、网络中断),配置Asp.Net Core会话与认证Cookie的超时时间,超时后自动清理会话并记录登出时间。
在Program.cs(或Startup.cs)中配置:
// 配置会话 services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(30); options.Cookie.HttpOnly = true; options.Cookie.IsEssential = true; }); // 配置认证Cookie services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.ExpireTimeSpan = TimeSpan.FromMinutes(30); options.Events = new CookieAuthenticationEvents { OnValidatePrincipal = async context => { var userManager = context.HttpContext.RequestServices.GetRequiredService<UserManager<IdentityUser>>(); var userId = context.Principal.FindFirstValue(ClaimTypes.NameIdentifier); var user = await userManager.FindByIdAsync(userId); if (user != null) { user.LastLogoutTime = DateTime.Now; await userManager.UpdateAsync(user); } } }; });
关键注意点
- 优先使用
navigator.sendBeacon替代普通AJAX,避免页面卸载时请求被浏览器拦截。 - 数据库写入操作建议添加事务,保证登出状态与时间记录的原子性。
- 接口添加
[Authorize]特性,确保只有已登录用户能触发登出逻辑。
内容的提问来源于stack exchange,提问作者Mehedi Hasan Kajol
相关产品推荐
相关产品推荐

