在我的应用程序中,我想检查特定用户是否登录,以便我可以显示一个状态,表明该用户对另一个用户“在线”或“离线”。这个问题不涉及对用户进行身份验证,仅涉及获取用户的身份验证状态。
我将如何实现这一目标?
最佳答案
我认为一个选择是使用一些实时解决方案。 SignalR例如。 当用户登录时,您将其连接到集线器。 OnConnected() 操作保存其状态。然后 OnDisconnected() 从“OnlineRepository”中删除。
用示例更新 以下是我在 ASP.Net Mvc 5 应用程序中执行此操作的方法。
包含单个用户的模型类,例如:
public class SingleConnection { public SingleConnection() { ConnectionId = new List(); } public string Id { get; set; } public List ConnectionId { get; set; } }
连接映射类,有助于从列表中添加/删除和获取用户
public class ConnectionMapping { private readonly List _connections = new List(); public int Count { get { return _connections.Count; } } public void Add(string key, string connectionId) { lock (_connections) { var sn = _connections.Where(x => x.Id == key).FirstOrDefault(); if (sn != null) // there is a connection with this key { _connections.Find(x => x.Id == key).ConnectionId.Add(connectionId); } else { _connections.Add(new SingleConnection { Id = key, ConnectionId = new List { connectionId } }); } } } public List GetConnections(string id) { var con = _connections.Find(x => x.Id == id); return con != null ? con.ConnectionId : new List(); } public List AllConnectionIds() { List results = new List(); var allItems = _connections.Where(x => x.ConnectionId.Count > 0).ToList(); foreach (var item in allItems) { results.AddRange(item.ConnectionId); } return results; } public List AllKeys() { return _connections.Select(x => x.Id).ToList(); } public void Remove(string key, string connectionId) { lock (_connections) { var item = _connections.Find(x => x.Id == key); if (_connections.Find(x => x.Id == key) != null) { _connections.Find(x => x.Id == key).ConnectionId.Remove(connectionId); if (_connections.Find(x => x.Id == key).ConnectionId.Count == 0) { _connections.Remove(item); } } } } }
- 在我的 Hub 类中
private void IsActive(string connection, bool connected) { Clients.All.clientconnected(connection, connected); } public override Task OnConnected() { string name = Context.User.Identity.Name; _connections.Add(name, Context.ConnectionId); IsActive(name, true); return base.OnConnected(); } public override Task OnDisconnected(bool stopCalled) { string name = Context.User.Identity.Name; _connections.Remove(name, Context.ConnectionId); IsActive(name, false); return base.OnDisconnected(stopCalled); } public override Task OnReconnected() { string name = Context.User.Identity.Name; if (!_connections.GetConnections(name).Contains(Context.ConnectionId)) { _connections.Add(name, Context.ConnectionId); } IsActive(name, false); return base.OnReconnected(); }
在_Layout.cshtml中
// reference scripts // add a callback or the OnConnected() Will not fire chat.client.clientconnected = function (id,active){ /* this will be called everytime a user connect or disconnect to the hub */ } $.connection.hub.start();
现在,我可以实时获取所有在线用户。
注意:这是一个 InMemory 解决方案。其他解决方案是 here
希望这有帮助...
关于c# - ASP.NET MVC - 获取用户的登录状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36555165/