SignalR-向特定用户发送推送通知

时间:2020-07-28 04:42:15

标签: signalr

我正在为通知引擎开发PoC。我能够从JS成功连接并调用Hub函数,但似乎无法使推送通知正常工作。我遇到Object reference not set to an instance of an object错误。

触发类

//我能够确认connectionIds有效

   public void HandleEvent(NewNotificationEvent eventMessage)
   {
        // _connections handles connectionids of a user
        // multiple connection ids to handle multiple open tabs
        var connectionIds = _connections.GetConnectionsByUser(eventMessage.Notification.UserId);

        foreach(var connectionId in connectionIds)
        {
            // a client is returned, but aside from the connectionid, all the properties are either null or empty
            var client = _notificationHub.Clients.Client(connectionId);
            
            ///// ERROR HAPPENS HERE
            ///// I'm guessing NewNotification() isn't defined somewhere, but I don't know where.
            client.NewNotification("Hello");
        }
    }

View.cshtml

    var notificationHub = $.connection.NotificationHub;
    $.connection.hub.qs="userId=@userId"

    // Initialization
    $.connection.hub.start().done(function () {
        // get count unread notification count
        notificationHub.invoke("unReadNotificationsCount")
            .done((unreadCount) => {
                if (unreadCount > 0) {
                    $('#notificationBadge').html(unreadCount);
                    hasNewNotification = true;
                }
                console.log('SignalR connected!');
            })
            .fail((data) => {
                console.log('Unable to reach server');
                console.log(data);
            })
            .always(() => $('#dropdownNotificationOptions').show());
      
    });
    // also tried notificationHub.NewNotification()
    notificationHub.client.NewNotification = function (notification) {
        console.log(notification);
    }

NotificationHub.cs

[HubName("NotificationHub")]
public class NotificationHub : Hub
{

    //ctor
    public override Task OnConnected()
    {
        var userId = Context.QueryString["userid"];
        if(userId.IsNotNullOrEmpty())
        _connections.Add(Context.ConnectionId, Guid.Parse(userId));
        else
            _connections.Add(Context.ConnectionId, Guid.NewGuid());
        return base.OnConnected();
    }
    

    public override Task OnDisconnected(bool stopCalled = true)
    {
        _connections.Remove(Context.ConnectionId);
        return base.OnDisconnected(stopCalled);
    }
    public override Task OnReconnected()
    {
        Guid userId;
        if (Guid.TryParse(Context.QueryString["userid"],out userId))
        {
            //var userId = _workContext.CurrentUser.Id;
            var userConnection = _connections.GetUserByConnection(Context.ConnectionId);
            if (userConnection == null || userConnection.IsNotNullOrEmpty())
            { 
                _connections.Add(Context.ConnectionId, userId);
            }
        }
       

        return base.OnReconnected();
    }
}

1 个答案:

答案 0 :(得分:1)

您应该在$ .connection.hub.start()之前输入NewNotification,例如:

var notificationHub = $.connection.NotificationHub;
$.connection.hub.qs="userId=@userId"

// Moved to define before the connection start
notificationHub.client.NewNotification = function (notification) {
    console.log(notification);
}

// Initialization
$.connection.hub.start().done(function () {
    // get count unread notification count
    notificationHub.invoke("unReadNotificationsCount")
        .done((unreadCount) => {
            if (unreadCount > 0) {
                $('#notificationBadge').html(unreadCount);
                hasNewNotification = true;
            }
            console.log('SignalR connected!');
        })
        .fail((data) => {
            console.log('Unable to reach server');
            console.log(data);
        })
        .always(() => $('#dropdownNotificationOptions').show());
  
});