使用asp.net和c#自动更新在线/离线成员状态

本文关键字:在线 离线 成员 状态 更新 net asp 使用 | 更新日期: 2023-09-27 18:04:11

我使用一个表(我们称之为T_User),其中包含描述每个用户的字段。其中一个字段是"Status",这个字段在用户每次登录(或者当他连接到我的网站时已经登录)时更新为true,并且在用户离开页面时自动更新为false(无论用户是否注销)。对于这个问题,我提出的解决方案是使用Quartz.net创建一个调度器,该调度器将检查在线用户的所有session_id,以确定会话是否存在!我的问题是,我找不到一个有效的方法来确定如果会话是活的!那么如何获取每个用户的会话状态呢?有没有更好的方法来实现这个"功能"?谢谢你的回答

使用asp.net和c#自动更新在线/离线成员状态

我在一个项目中需要类似的东西。我使用SignalR来查看我的web应用程序上有多少当前连接。

的例子:

[HubName("trackingHub")]
public class TrackingHub : Hub
{
    public void SendCount()
    {   // Send the ConnectedUsers count to the caller
        Clients.All.count(SignalRConnectionHandler.ConnectedUsers.Count);
    }
    public override Task OnConnected()
    {
        // When a user connects, add him to the HashSet
        SignalRConnectionHandler.ConnectedUsers.Add(Context.ConnectionId);
        SendCount();
        return base.OnConnected();
    }
    public override Task OnDisconnected(bool stopCalled)
    {
        // When a user disconnects, remove him to the Hashset
        SignalRConnectionHandler.ConnectedUsers.Remove(Context.ConnectionId);
        SendCount();
        return base.OnDisconnected(stopCalled);
    }
    public override Task OnReconnected()
    {
        // When a user reconnects, Check if he is already in the Hashset, if not add him back in.
        if (!SignalRConnectionHandler.ConnectedUsers.Contains(Context.ConnectionId))
        {
            SignalRConnectionHandler.ConnectedUsers.Add(Context.ConnectionId);
        }
        return base.OnReconnected();
    }
<<p> 连接处理器/strong>
public static class SignalRConnectionHandler
{
    public static HashSet<string> ConnectedUsers = new HashSet<string>();
}
<<p> 视图/strong>
 $(function () {
        var hub = $.connection.trackingHub; 
        hub.client.count = function(count) {
            $('#count').html(count); // Append the connected users count to the page
        }
        // Connect the user to the Hub
        $.connection.hub.start().done(function () {
            console.log("connected");
        });
    });

如果您在_layout中添加hub.start()ConnectedUsers散列现在将包含所有连接的userId。因为我们可以覆盖Hub上的一些方法,所以我们可以在有人连接和断开连接时设置ConnectedUsers

正如您所看到的,我将所有内容存储在HashSet<T>中,但您可以将其存储在DB等(请注意,将其存储在如上所述的内存中,一旦IIS回收则对象将丢失)