从控制器的操作中调用集线器方法 [英] Call a hub method from a controller's action
问题描述
如何从控制器的操作中调用集线器方法?这样做的正确方法是什么?
有人在帖子中使用过这个:
DefaultHubManager hd = new DefaultHubManager(GlobalHost.DependencyResolver);var hub = hd.ResolveHub("AdminHub") as AdminHub;hub.SendMessage("woohoo");
但对我来说,那就是投掷:
<块引用>不支持使用不是由 HubPipeline 创建的 Hub 实例.
我还读到您可以创建一个集线器上下文,但我不想将责任赋予该操作,即该操作执行以下操作:
hubContext.Client(...).someJsMethod(..)
正确的方法是实际创建集线器上下文.如何以及在何处执行此操作取决于您,这里有两种方法:
在您的集线器中创建一个静态方法(不必在您的集线器中,实际上可以在任何地方)然后您可以通过
<块引用>AdminHub.SendMessage("wooo") 调用它
代码>public static void SendMessage(string msg){var hubContext = GlobalHost.ConnectionManager.GetHubContext
();hubContext.Clients.All.foo(msg);} 完全避免静态方法,直接发送到集线器客户端
<块引用>var hubContext = GlobalHost.ConnectionManager.GetHubContext
();hubContext.Clients.All.foo(msg);
How can I call a hub method from a controller's action? What is the correct way of doing this?
Someone used this in a post:
DefaultHubManager hd = new DefaultHubManager(GlobalHost.DependencyResolver);
var hub = hd.ResolveHub("AdminHub") as AdminHub;
hub.SendMessage("woohoo");
But for me, that is throwing:
Using a Hub instance not created by the HubPipeline is unsupported.
I've read also that you can create a hub context, but I don't want to give the responsability to the action, that is, the action doing stuff like:
hubContext.Client(...).someJsMethod(..)
The correct way is to actually create the hub context. How and where you do that is up to you, here are two approachs:
Create a static method in your hub (doesn't have to be in your hub, could actually be anywhere) and then you can just call it via
AdminHub.SendMessage("wooo")
public static void SendMessage(string msg) { var hubContext = GlobalHost.ConnectionManager.GetHubContext<AdminHub>(); hubContext.Clients.All.foo(msg); }
Avoid the static method all together and just send directly to the hubs clients
var hubContext = GlobalHost.ConnectionManager.GetHubContext<AdminHub>(); hubContext.Clients.All.foo(msg);
这篇关于从控制器的操作中调用集线器方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!