【问题标题】:signalR invoke from event in server-sidesignalR 从服务器端的事件调用
【发布时间】:2019-09-26 13:25:24
【问题描述】:

我创建了一个与 signalR 一起使用的通知系统,还创建了一个在添加通知后立即发生的事件。我想从同一事件中调用我的notifictionHub 中的函数我已经看到一些对我正在使用的版本无效的解决方案,我想知道我该怎么做?

通知中心:

        public async Task SendNotification(string user, string content)
        {
            string userID = "3";
            foreach(var cid in _connections.GetConnections(userID))
            {
                await Clients.Client(cid).SendAsync("ReceiveNotification", user, content);
            }
        }

添加通知事件:

        private static void Notifications_OnNotificationAdd(Account account, Notification notification)
        {
            // call NotificationHub->SendNotification from here...  
        }

【问题讨论】:

    标签: asp.net .net .net-core notifications signalr


    【解决方案1】:

    在您的活动课程中:

    //using this instance object, we are able to access and call the hub methods.
    private IHubContext<notifictionHub> _hub;
    

    在你的事件方法中:

    private static void Notifications_OnNotificationAdd(Account account, Notification notification)
    {
       _hub.Clients.All.SendNotification(yourUser, yourContent);
    }
    

    【讨论】:

    • 感谢您的回答,当我尝试执行您的解决方案时,我收到此错误:`非静态字段、方法或属性'Notifications._hub'需要对象引用`当我尝试将其设置为静态时,它为空并且它使我的程序崩溃:(@Praetorian1995
    • 如果这不起作用,您可以使用 GlobalHost,例如:rivate static IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext&lt;NotificationHub&gt;();
    • 尝试使用 readonly 之前给了我同样的错误,我读到 GlobalHost 它不适合我的程序,因为我使用的是 net-core。
    • 也许现在缺少的是构造函数。 public yourClass(IHubContext&lt;notificationHub&gt; hubContext) { _hub = hubContext; }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-30
    • 1970-01-01
    • 2011-11-03
    • 2022-01-19
    相关资源
    最近更新 更多