如何将数据与 .NET Core 中的 SignalR 连接相关联?

How do I associate data with a SignalR connection in .NET Core?

在我的旧 SignalR(核心前)项目中,我曾经有一个 static ConcurrentDictionary<string, MyConnectionClass> Connections = new ...; 来表示我的个人连接以及在连接生命周期内获取的额外数据。

如何在 SignalR for .NET Core 中解决这个问题?

我正在看这本手册:https://medium.com/@andrejsabrickis/recap-creating-a-demo-of-real-time-communication-app-using-aspnetcore-signalr-d8ac0afba081

使用以下内容:

private readonly ConcurrentDictionary<HubConnectionContext, UserDetails> _usersOnline;

现在,我想知道是否应该使用 HubConnectionContext 作为键。使用安全吗?只要连接可行,该实例是否始终与连接 ID 相关联?我没有使用任何类型的负载平衡。

Now, I'm wondering if I should use the HubConnectionContext as a key. Is it safe to use? Will that instance always be associated with the connection id for as long as the connection is viable?

没有。那篇文章描述的实现实际使用:

  1. ConcurrentDictionary<string, UserDetailsDto>

  2. _userTracker.AddUser(connection.ConnectionId, new UserDetailsDto (...))

connection.ConnectionId 使用安全且足以将数据与连接相关联。