I have ASP NET Core web API and use SignalR. I have 3 separate hubs, and MessageHub
one of them. Here is the code:
public class MessageHub : Hub
{
public MessageHub() { }
static List<UserDetail> ConnectedUsers = new List<UserDetail>();
public override Task OnConnectedAsync()
{
var userId = Context.UserIdentifier;
var id = Context.ConnectionId;
ConnectedUsers.Add(new UserDetail { ConnectionId = id, UserID = userId });
return base.OnConnectedAsync();
}
public override Task OnDisconnectedAsync(Exception exception)
{
var id = Context.ConnectionId;
UserDetail userDetail = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == id);
if (userDetail != null)
{
ConnectedUsers.Remove(userDetail);
}
return base.OnDisconnectedAsync(exception);
}
}
UserDetails:
public class UserDetail
{
public string ConnectionId { get; set; }
public string UserID { get; set; }
}
I using overrided method for connecting and disconnecting, and it works well, but the problem is that sometimes, after an hour or day, problem appears. I start get this error in logger:
|ERROR|Microsoft.AspNetCore.SignalR.HubConnectionHandler|Error when dispatching 'OnConnectedAsync' on hub. System.NullReferenceException: Object reference not set to an instance of an object.
What can be the issue? Restarting fix this problem for a while but then it comes back.