Call a hub method from a controller's action

↘锁芯ラ 提交于 2019-12-18 10:59:32

问题


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(..)

回答1:


The correct way is to actually create the hub context. How and where you do that is up to you, here are two approachs:

  1. 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);
    }
    
  2. 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);
    


来源:https://stackoverflow.com/questions/17395201/call-a-hub-method-from-a-controllers-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!