How do I call a SignalR hub method from the outside?

后端 未结 3 853
有刺的猬
有刺的猬 2020-12-30 03:53

This is my Hub code:

public class Pusher : Hub, IPusher
{
    readonly IHubContext _hubContext = GlobalHo         


        
3条回答
  •  我在风中等你
    2020-12-30 04:23

    You can't instantiate and call a hub class directly like that. There is much plumbing provided around a Hub class by the SignalR runtime that you are bypassing by using it as a "plain-old class" like that.

    The only way to interact with a SignalR hub from the outside is to actually get an instance of an IHubContext that represents the hub from the SignalR runtime. You can only do this from within the same process, so as long as your other "project" is going to be running in process with the SignalR code it will work.

    If your other project is going to be running in another process then what you would want to do is expose a sort of "companion" API which is either another SignalR hub or a regular old web service (with ASP.NET web API) that you can call from this other application to trigger the behavior you want. Whichever technology you choose, you would probably want to secure this so that only your authenticated applications can call it.

    Once you decide which approach you're going to take, all you would do to send messages out via the Pusher hub would be:

    // Get the context for the Pusher hub
    IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext();
    
    // Notify clients in the group
    hubContext.Clients.Group(group).GetData(data);
    

提交回复
热议问题