1

我有一个 MVC 3、VB.NET、Razor 应用程序,它使用 SignalR 进行聊天和系统消息系统......聊天工作完美,但我希望能够在我的管理控制器中添加一个功能,将消息发送到集线器然后将执行其正常操作,就好像 Javascript 从视图中调用它一样...集线器设置如下:

Imports SignalR.Hubs
Imports SignalR

Namespace SingalRTest
 Public Class Chat
    Inherits Hub
    Public Sub Send(ByVal clientName As String, ByVal message As String)
        'Call the addMessage method on all clients.
        Clients.addMessage(clientName, message)
    End Sub

 End Class
End Namespace

我考虑过简单地使用 NEW 但这行不通,因为据我了解,集线器的实例必须保持不变..

我想做的是这样的:

 Public Function notification(ByVal systemMessage as string)
        Dim y As SingalRTest.Chat = Nothing
        y.Send(User.Identity.Name.ToString, systemMessage)
        Return RedirectToAction("Index", "Admin")
 End Function

这根本不起作用,错误说:

  Object reference not set to an instance of an Object

当它到达 y.Send 线时...

4

1 回答 1

3

哇,这花了很多时间在互联网上找到。我只需要在我的 Hub 类中添加一个共享子类,现在看起来像这样:

Imports SignalR.Hubs
Imports SignalR

Namespace SingalRTest

Public Class Chat
    Inherits Hub
    Public Sub Send(ByVal clientName As String, ByVal message As String)
        'Call the addMessage method on all clients.
        Clients.addMessage(clientName, message)
    End Sub
    Friend Shared Sub SendMessage(message As String)
        Dim context As IHubContext = GlobalHost.ConnectionManager.GetHubContext(Of Chat)()
        context.Clients.addMessage("System Message", message)
    End Sub
End Class

End Namespace

然后,每当我想在窗口中发送通知时,我只需将此代码放在控制器函数中即可在所有客户端上调用 addMessage 方法:

    SingalRTest.Chat.SendMessage("Testing Only")

也许这会帮助别人。

于 2012-08-25T01:30:55.360 回答