【发布时间】:2017-06-04 06:11:21
【问题描述】:
我正在使用 SignalR 和 MVC 在用户访问网站时向他们推送通知。只要我将通知发送给所有人,它就可以工作,但是当我尝试隔离用户时,我什么也得不到。两边都没有抛出错误,它只是默默地失败了。
这是我的 Hub 代码:
public class NotificationHub : Hub
{
private readonly static IDictionary<int, string> _connections = new Dictionary<int, string>();
public static void AddNotification(int userId, Notification notification)
{
if (notification != null)
{
string userConnectionId = null;
_connections.TryGetValue(userId, out userConnectionId);
//Send message only if the user is currently connected.
if (userConnectionId != null)
{
IHubContext hub = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
hub.Clients.Client(userConnectionId)
.addNotification(
notification.ID,
notification.ShowMessage(),
notification.Link);
}
}
}
public override Task OnConnected()
{
if(_connections.ContainsKey(WebSecurity.CurrentUserId))
{
_connections[WebSecurity.CurrentUserId] = Context.ConnectionId;
}
else
{
_connections.Add(WebSecurity.CurrentUserId, Context.ConnectionId);
}
return base.OnConnected();
}
}
这是我的 JS 代码:
var notificationConnection = $.connection.notificationHub;
notificationConnection.client.addNotification = function (id, message, link) {
alert(message);
};
$.connection.hub.start().done(function () { });
连接 ID 似乎有问题,但我在某种程度上遵循了 SignalR 页面上的示例:https://www.asp.net/signalr/overview/guide-to-the-api/mapping-users-to-connections
编辑:
只是为了澄清。如果我更换:
hub.Clients.Client(userConnectionId)
.addNotification(
notification.ID,
notification.ShowMessage(),
notification.Link);
与:
hub.Clients.All
.addNotification(
notification.ID,
notification.ShowMessage(),
notification.Link);
它有效。
所以问题似乎出在这一行:hub.Clients.Client(userConnectionId)
我还确保在函数运行时填充了 userConnectionId,而且确实如此。
【问题讨论】:
标签: jquery asp.net asp.net-mvc signalr