Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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(..)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
658 views
Welcome To Ask or Share your Answers For Others

1 Answer

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);
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...