SignalR + 通过操作方法将消息发布到集线器 [英] SignalR + posting a message to a Hub via an action method
问题描述
我正在使用 SignalR 的集线器功能(https://github.com/SignalR/SignalR) 向所有订阅的客户端发布消息:
I am using the hub- feature of SignalR (https://github.com/SignalR/SignalR) to publish messages to all subscribed clients:
public class NewsFeedHub : Hub
public void Send(string channel, string content)
{
Clients[channel].addMessage(content);
}
这在通过 Javascript 调用发送"时工作正常,但我也希望 Web 应用程序发布消息(从 ASP.NET MVC 操作方法中).我已经尝试实例化一个新对象 ob NewsFeedHub 并调用 Send 方法,但这会导致错误(因为未设置集线器的基础连接").有没有办法在没有连接的情况下使用集线器?
This works fine when calling "Send" via Javascript, but I would also like the web application to publish messages (from within an ASP.NET MVC action method). I already tried instantiating a new object ob NewsFeedHub and calling the Send method, but this results in an error (as the underlying "Connection" of the Hub is not set). Is there a way to use the Hub without a connection?
推荐答案
请注意,自提出此问题以来,SignalR API 已更改多次.有些答案可能会过时.这并不意味着他们应该被否决,因为他们在撰写本文时是正确的
对此还有另一个更新的答案,如SignalR 维基
There is another updated answer for this, as seen in the SignalR Wiki
c#
Public ActionResult MyControllerMethod()
{
var context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
context.Clients.All.methodInJavascript("hello world");
// or
context.Clients.Group("groupname").methodInJavascript("hello world");
}
vb.net
Public Function MyControllerMethod() As ActionResult
Dim context = GlobalHost.ConnectionManager.GetHubContext(Of MyHub)()
context.Clients.All.methodInJavascript("hello world")
'' or
context.Clients.Group("groupname").methodInJavascript("hello world")
End Function
更新
此代码已更新.关注 http://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-server 用于更改.
This code has been updated. Follow http://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-server for changes.
如果您使用的是 DI 容器
如果您使用 DI 容器来连接集线器,请从您的容器中获取 IConnectionManager
,然后在该 connectionManager 上调用 GetHubContext
.
If you are using a DI container to wire up your hubs, get IConnectionManager
from your container, and call GetHubContext
on that connectionManager.
这篇关于SignalR + 通过操作方法将消息发布到集线器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!