【发布时间】:2021-03-11 07:27:46
【问题描述】:
当使用 SignalR 向特定用户发送通知时,它不起作用。
我将连接 ID 存储在一个表中,当应该发送通知时,我从数据库中获取了接收者的连接 ID,但他什么也没得到。我的代码有什么问题?
// get the connectionId of the receiver
if (_db.UserConnectionid != null)
{
var userConn = await _db.UserConnectionid.Where(x => x.UserId == receiver).Select(x => x.ConnectionId).FirstOrDefaultAsync();
//if the receiver is online
if (userConn != null)
{
await Clients.Client(userConn).SendAsync("RecieveMessage", message);
}
}
【问题讨论】:
-
如果有UserId,可以直接试试Clients.User(receiver).SendAsync(...)
-
这可能是由于多种不同的原因,数据库中陈旧的连接 ID 或者特别是在 SPA 的情况下,如果您在不同页面中创建了多个连接对象并且没有清理和关闭这些连接在离开页面之前。您发送的消息将始终由您首先创建的对象接收。这是我大部分麻烦的原因。
标签: entity-framework asp.net-core signalr signalr-hub