feat: 添加SignalR登录状态管理功能
- 在Program.cs中注册LoginHub - 在HomeController中传递用户ID以支持SignalR连接 - 在Index.cshtml中实现SignalR连接和心跳机制,处理强制登出和注册成功事件 - 移除旧的登录状态检查逻辑,优化页面加载时的连接管理
This commit is contained in:
1 parent
0e5d0247bf
commit
c38199268f
9 files changed
+241
-48
No files matched your search
@@ -476,9 +476,9 @@ namespace HHWMS.Web
|
|||||||
container.LocationCode = task.TaskType == TaskTypeEnum.出库 ? "" : task.ToLocation;
|
container.LocationCode = task.TaskType == TaskTypeEnum.出库 ? "" : task.ToLocation;
|
||||||
container.IsLock = ContainerLockEnum.未锁;
|
container.IsLock = ContainerLockEnum.未锁;
|
||||||
container.UpdateTime = DateTime.Now;
|
container.UpdateTime = DateTime.Now;
|
||||||
}
|
|
||||||
|
|
||||||
_unitWork.Update(container);
|
_unitWork.Update(container);
|
||||||
|
}
|
||||||
|
|
||||||
// 更新库位状态(区分入库、出库、移库)
|
// 更新库位状态(区分入库、出库、移库)
|
||||||
switch (task.TaskType)
|
switch (task.TaskType)
|
||||||
|
|||||||
@@ -137,7 +137,7 @@
|
|||||||
|
|
||||||
// 根据库区加载排号
|
// 根据库区加载排号
|
||||||
function loadRows(area) {
|
function loadRows(area) {
|
||||||
console.log(area);
|
//console.log(area);
|
||||||
if (!area) return;
|
if (!area) return;
|
||||||
$.get('/configs/LocationMonitor/GetRows', { area: area }, function(data) {
|
$.get('/configs/LocationMonitor/GetRows', { area: area }, function(data) {
|
||||||
var rowSelect = $('#rowSelect');
|
var rowSelect = $('#rowSelect');
|
||||||
|
|||||||
@@ -0,0 +1,104 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Concurrent;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Microsoft.AspNetCore.SignalR;
|
||||||
|
|
||||||
|
namespace HHWMS.Web
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 登录状态 Hub - 用于保活和异地登录检测
|
||||||
|
/// </summary>
|
||||||
|
public class LoginHub : Hub
|
||||||
|
{
|
||||||
|
// 存储用户连接信息:用户ID -> 连接ID
|
||||||
|
private static readonly ConcurrentDictionary<string, string> _userConnections = new();
|
||||||
|
|
||||||
|
// 存储连接对应的用户:连接ID -> 用户ID
|
||||||
|
private static readonly ConcurrentDictionary<string, string> _connectionUsers = new();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 用户登录注册连接
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="userId">用户ID</param>
|
||||||
|
public async Task Register(string userId)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(userId))
|
||||||
|
return;
|
||||||
|
|
||||||
|
var connectionId = Context.ConnectionId;
|
||||||
|
|
||||||
|
// 检查该用户是否已有其他连接
|
||||||
|
if (_userConnections.TryGetValue(userId, out var oldConnectionId))
|
||||||
|
{
|
||||||
|
if (oldConnectionId != connectionId)
|
||||||
|
{
|
||||||
|
// 通知旧连接被踢出
|
||||||
|
await Clients.Client(oldConnectionId).SendAsync("ForceLogout", "您的账号已在其他设备登录");
|
||||||
|
|
||||||
|
// 移除旧连接记录
|
||||||
|
_connectionUsers.TryRemove(oldConnectionId, out _);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新连接映射
|
||||||
|
_userConnections[userId] = connectionId;
|
||||||
|
_connectionUsers[connectionId] = userId;
|
||||||
|
|
||||||
|
// 通知当前客户端注册成功
|
||||||
|
await Clients.Caller.SendAsync("RegisterSuccess", "连接成功");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 心跳保活
|
||||||
|
/// </summary>
|
||||||
|
public async Task Heartbeat(string userId)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(userId))
|
||||||
|
return;
|
||||||
|
|
||||||
|
var connectionId = Context.ConnectionId;
|
||||||
|
|
||||||
|
// 检查是否是当前有效连接
|
||||||
|
if (_userConnections.TryGetValue(userId, out var currentConnectionId))
|
||||||
|
{
|
||||||
|
if (currentConnectionId != connectionId)
|
||||||
|
{
|
||||||
|
// 当前连接不是最新的,通知被踢出
|
||||||
|
await Clients.Caller.SendAsync("ForceLogout", "您的账号已在其他设备登录");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 回复心跳
|
||||||
|
await Clients.Caller.SendAsync("HeartbeatResponse", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 连接断开时清理
|
||||||
|
/// </summary>
|
||||||
|
public override Task OnDisconnectedAsync(Exception exception)
|
||||||
|
{
|
||||||
|
var connectionId = Context.ConnectionId;
|
||||||
|
|
||||||
|
// 移除连接记录
|
||||||
|
if (_connectionUsers.TryRemove(connectionId, out var userId))
|
||||||
|
{
|
||||||
|
// 只有当前连接是该用户的有效连接时才移除用户映射
|
||||||
|
if (_userConnections.TryGetValue(userId, out var currentConnectionId) && currentConnectionId == connectionId)
|
||||||
|
{
|
||||||
|
_userConnections.TryRemove(userId, out _);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return base.OnDisconnectedAsync(exception);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取在线用户数量
|
||||||
|
/// </summary>
|
||||||
|
public int GetOnlineCount()
|
||||||
|
{
|
||||||
|
return _userConnections.Count;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -576,7 +576,7 @@ namespace HHWMS.Web.Controllers
|
|||||||
});
|
});
|
||||||
|
|
||||||
// 调用ERP接口
|
// 调用ERP接口
|
||||||
var apiResult = await Wtm.CallAPI<FinishInResponse>("ERP", "Api/FinishIn", HttpMethodEnum.POST, request);
|
var apiResult = await Wtm.CallAPI<FinishInResponse>("ERP", "FinishIn", HttpMethodEnum.POST, request);
|
||||||
|
|
||||||
if (apiResult.Data != null)
|
if (apiResult.Data != null)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ namespace HHWMS.Web.Controllers
|
|||||||
public IActionResult Index(string redirect)
|
public IActionResult Index(string redirect)
|
||||||
{
|
{
|
||||||
ViewData["title"] = "WMS";
|
ViewData["title"] = "WMS";
|
||||||
|
ViewData["ITCode"] = Wtm.LoginUserInfo?.ITCode; // 传递用户ID用于SignalR连接
|
||||||
return View();
|
return View();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -103,6 +103,7 @@ app.UseEndpoints(endpoints =>
|
|||||||
name: "default",
|
name: "default",
|
||||||
pattern: "{controller=Home}/{action=Index}/{id?}");
|
pattern: "{controller=Home}/{action=Index}/{id?}");
|
||||||
endpoints.MapHub<StockTickerHub>("/stocks");
|
endpoints.MapHub<StockTickerHub>("/stocks");
|
||||||
|
endpoints.MapHub<LoginHub>("/loginHub");
|
||||||
});
|
});
|
||||||
// 添加以下代码以确保响应是UTF-8编码
|
// 添加以下代码以确保响应是UTF-8编码
|
||||||
app.Use(async (context, next) =>
|
app.Use(async (context, next) =>
|
||||||
|
|||||||
@@ -56,7 +56,7 @@
|
|||||||
initLocationChart();
|
initLocationChart();
|
||||||
initCurrentTaskChart();
|
initCurrentTaskChart();
|
||||||
});
|
});
|
||||||
console.log(echarts);
|
//console.log(echarts);
|
||||||
// 一周内出入库任务统计柱状图
|
// 一周内出入库任务统计柱状图
|
||||||
function initTaskHistoryChart() {
|
function initTaskHistoryChart() {
|
||||||
var taskHistoryChart = echarts.init(document.getElementById('taskHistoryChart'));
|
var taskHistoryChart = echarts.init(document.getElementById('taskHistoryChart'));
|
||||||
|
|||||||
@@ -1,57 +1,144 @@
|
|||||||
<script>layui.use('index')</script>
|
<script>layui.use('index')</script>
|
||||||
|
<script src="/front/signalr.min.js"></script>
|
||||||
<script>
|
<script>
|
||||||
// 检查登录状态的函数
|
// SignalR 登录状态管理
|
||||||
function checkLoginStatus() {
|
var loginConnection = null;
|
||||||
$.ajax({
|
var heartbeatTimer = null;
|
||||||
url: '/Home/CheckLogin',
|
var userId = '@ViewData["ITCode"]'; // 从后端获取当前用户ID
|
||||||
type: 'GET',
|
var isForceLogout = false;
|
||||||
success: function(data) {
|
|
||||||
// 如果返回的数据包含Login,说明已被重定向到登录页
|
|
||||||
if (data && data.indexOf('Login') !== -1) {
|
|
||||||
// 清除定时器
|
|
||||||
if (window.loginCheckTimer) {
|
|
||||||
clearInterval(window.loginCheckTimer);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 使用layer弹窗提示
|
// 初始化 SignalR 连接
|
||||||
layer.alert("您的账号已在其他设备登录,请重新登录", {
|
function initLoginHub() {
|
||||||
icon: 0,
|
loginConnection = new signalR.HubConnectionBuilder()
|
||||||
title: "登录提示",
|
.withUrl("/loginHub")
|
||||||
closeBtn: 0,
|
.withAutomaticReconnect([0, 2000, 5000, 10000, 30000]) // 自动重连策略
|
||||||
btn: ['确定'],
|
.build();
|
||||||
yes: function(index) {
|
|
||||||
layer.close(index);
|
// 监听强制登出事件
|
||||||
// 重定向到登录页
|
loginConnection.on("ForceLogout", function(message) {
|
||||||
window.location.href = '/Login/Login';
|
isForceLogout = true;
|
||||||
}
|
stopHeartbeat();
|
||||||
});
|
|
||||||
|
// 使用layer弹窗提示
|
||||||
|
layer.alert(message || "您的账号已在其他设备登录,请重新登录", {
|
||||||
|
icon: 0,
|
||||||
|
title: "登录提示",
|
||||||
|
closeBtn: 0,
|
||||||
|
btn: ['确定'],
|
||||||
|
yes: function(index) {
|
||||||
|
layer.close(index);
|
||||||
|
// 重定向到登录页
|
||||||
|
window.location.href = '/Login/Login';
|
||||||
}
|
}
|
||||||
},
|
});
|
||||||
error: function(xhr) {
|
});
|
||||||
// 如果返回401或其他错误,直接跳转到登录页
|
|
||||||
window.location.href = '/Login/Login';
|
// 监听注册成功
|
||||||
|
loginConnection.on("RegisterSuccess", function(message) {
|
||||||
|
console.log("SignalR 登录连接成功:", message);
|
||||||
|
startHeartbeat();
|
||||||
|
});
|
||||||
|
|
||||||
|
// 监听心跳响应
|
||||||
|
loginConnection.on("HeartbeatResponse", function(serverTime) {
|
||||||
|
//console.log("心跳响应:", serverTime);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 连接关闭事件
|
||||||
|
loginConnection.onclose(function(error) {
|
||||||
|
console.log("SignalR 连接已关闭", error);
|
||||||
|
stopHeartbeat();
|
||||||
|
|
||||||
|
if (!isForceLogout) {
|
||||||
|
// 非强制登出,尝试重连
|
||||||
|
setTimeout(function() {
|
||||||
|
startConnection();
|
||||||
|
}, 5000);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 重连成功事件
|
||||||
|
loginConnection.onreconnected(function(connectionId) {
|
||||||
|
console.log("SignalR 重连成功:", connectionId);
|
||||||
|
// 重新注册
|
||||||
|
if (userId) {
|
||||||
|
loginConnection.invoke("Register", userId).catch(function(err) {
|
||||||
|
console.error("重新注册失败:", err);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 开始连接
|
||||||
|
startConnection();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 页面加载完成后开始检查
|
// 启动连接
|
||||||
$(document).ready(function() {
|
function startConnection() {
|
||||||
// 存储定时器ID
|
if (isForceLogout) return;
|
||||||
window.loginCheckTimer = setInterval(function() {
|
|
||||||
checkLoginStatus();
|
|
||||||
}, 10000); // 每10秒检查一次
|
|
||||||
|
|
||||||
// 页面关闭时清除定时器
|
loginConnection.start()
|
||||||
$(window).on('unload', function() {
|
.then(function() {
|
||||||
if (window.loginCheckTimer) {
|
console.log("SignalR 连接已建立");
|
||||||
clearInterval(window.loginCheckTimer);
|
// 注册当前用户
|
||||||
|
if (userId) {
|
||||||
|
loginConnection.invoke("Register", userId).catch(function(err) {
|
||||||
|
console.error("注册失败:", err);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(function(err) {
|
||||||
|
console.error("SignalR 连接失败:", err);
|
||||||
|
// 连接失败,5秒后重试
|
||||||
|
setTimeout(function() {
|
||||||
|
startConnection();
|
||||||
|
}, 5000);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 开始心跳
|
||||||
|
function startHeartbeat() {
|
||||||
|
stopHeartbeat();
|
||||||
|
heartbeatTimer = setInterval(function() {
|
||||||
|
if (loginConnection && loginConnection.state === signalR.HubConnectionState.Connected) {
|
||||||
|
loginConnection.invoke("Heartbeat", userId).catch(function(err) {
|
||||||
|
console.error("心跳发送失败:", err);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}, 30000); // 每30秒发送一次心跳
|
||||||
|
}
|
||||||
|
|
||||||
|
// 停止心跳
|
||||||
|
function stopHeartbeat() {
|
||||||
|
if (heartbeatTimer) {
|
||||||
|
clearInterval(heartbeatTimer);
|
||||||
|
heartbeatTimer = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 页面加载完成后初始化
|
||||||
|
$(document).ready(function() {
|
||||||
|
if (userId) {
|
||||||
|
initLoginHub();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 页面关闭时断开连接
|
||||||
|
$(window).on('beforeunload', function() {
|
||||||
|
if (loginConnection) {
|
||||||
|
loginConnection.stop();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// 页面从隐藏状态变为可见时,立即检查一次
|
// 页面从隐藏状态变为可见时,检查连接状态
|
||||||
$(document).on('visibilitychange', function() {
|
$(document).on('visibilitychange', function() {
|
||||||
if (document.visibilityState === 'visible') {
|
if (document.visibilityState === 'visible' && !isForceLogout) {
|
||||||
checkLoginStatus();
|
if (loginConnection && loginConnection.state !== signalR.HubConnectionState.Connected) {
|
||||||
|
startConnection();
|
||||||
|
} else if (loginConnection && userId) {
|
||||||
|
// 页面可见时发送一次心跳
|
||||||
|
loginConnection.invoke("Heartbeat", userId).catch(function(err) {
|
||||||
|
console.error("心跳发送失败:", err);
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -75,7 +75,7 @@
|
|||||||
margin-bottom: 1%;
|
margin-bottom: 1%;
|
||||||
">© 2022 华恒工程技术中心有限公司</p>*@
|
">© 2022 华恒工程技术中心有限公司</p>*@
|
||||||
</div>
|
</div>
|
||||||
<script>
|
@* <script>
|
||||||
var loginData = [];
|
var loginData = [];
|
||||||
$.post('/Home/BeforeLogin/',{},function (data){
|
$.post('/Home/BeforeLogin/',{},function (data){
|
||||||
loginData = data.Data;
|
loginData = data.Data;
|
||||||
@@ -101,7 +101,7 @@
|
|||||||
})
|
})
|
||||||
|
|
||||||
return issigned;
|
return issigned;
|
||||||
}
|
} *@
|
||||||
|
|
||||||
|
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
Reference in new issue
Block a user