Use Hub methods from controller?

前端 未结 2 599
逝去的感伤
逝去的感伤 2020-12-15 20:31

I am using SignalR 2 and I can not figure out how I can use my Hub methods e.g from inside a controller action.

I know I can do the following:

var hu         


        
2条回答
  •  余生分开走
    2020-12-15 21:06

    It might work to create a "helper" class that implements your business rules and is called by both your Hub and your Controller:

    public class MyHub : Hub
    {
        public void DoSomething()
        {
            var helper = new HubHelper(this);
            helper.DoStuff("hub stuff");
        }
    }
    
    public class MyController : Controller
    {
        public ActionResult Something()
        {
            var hub = GlobalHost.ConnectionManager.GetHubContext();
            var helper = new HubHelper(hub);
            helper.DoStuff("controller stuff");
        }
    }
    
    public class HubHelper
    {
        private IHubConnectionContext hub;
    
        public HubHelper(IHubConnectionContext hub)
        {
            this.hub = hub;
        }
    
        public DoStuff(string param)
        {
            //business rules ...
    
            hub.Clients.All.clientSideMethod(param);
        }
    }
    

提交回复
热议问题