asp.net-mvc 从控制器的操作中调用集线器方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17395201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call a hub method from a controller's action
提问by sports
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.
不支持使用不是由 HubPipeline 创建的 Hub 实例。
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(..)
回答by N. Taylor Mullen
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);
在您的集线器中创建一个静态方法(不必在您的集线器中,实际上可以在任何地方)然后您可以通过调用它
AdminHub.SendMessage("wooo")public static void SendMessage(string msg) { var hubContext = GlobalHost.ConnectionManager.GetHubContext<AdminHub>(); hubContext.Clients.All.foo(msg); }避免使用静态方法,直接发送到集线器客户端
var hubContext = GlobalHost.ConnectionManager.GetHubContext<AdminHub>(); hubContext.Clients.All.foo(msg);
回答by Hyman
As per aspnet3.1
根据 aspnet3.1
This differs from ASP.NET 4.x SignalR which used GlobalHost to provide access to the IHubContext. ASP.NET Core has a dependency injection framework that removes the need for this global singleton.
这与 ASP.NET 4.x SignalR 不同,后者使用 GlobalHost 提供对 IHubContext 的访问。ASP.NET Core 有一个依赖注入框架,不需要这个全局单例。
The correct way to do this is by Dependency Injection. You can read more about that here.
正确的方法是使用依赖注入。您可以在此处阅读更多相关信息。
https://docs.microsoft.com/en-us/aspnet/core/signalr/hubcontext?view=aspnetcore-3.1
https://docs.microsoft.com/en-us/aspnet/core/signalr/hubcontext?view=aspnetcore-3.1

