SignalR: How to truly call a hub's method from the server / C#

前端 未结 2 887
囚心锁ツ
囚心锁ツ 2021-02-07 04:17

I\'m trying to improve my application which will require calling a hub from C# instead of javascript. The current workflow for adding a task in my app is:

  • make an
2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-07 04:57

    I am using the method explained in this answer.

    public class NewsFeedHub : Hub 
    {
        private static IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext();
    
        // Call this from JS: hub.client.send(channel, content)
        public void Send(string groupName, string content)
        {
            Clients.Group(groupName).addMessage(content);
        }
    
        // Call this from C#: NewsFeedHub.Static_Send(groupName, content)
        public static void Static_Send(string groupName, string content)
        {
            hubContext.Clients.Group(groupName).addMessage(content);
        }
    
    }
    

    The hub defines and uses its hubContext, so you can do:

    var newsFeedHub = new NewsFeedHub();
    var newsFeedHub.Static_Send("ch1", "HELLO");
    

    Or:

    var taskHub = new TaskHub();
    var taskHub.InsertTask(task);
    

    If you prefer that, based on your method naming.

提交回复
热议问题