Send a signalr message from the server to all clients

This is due to SignalR + sending a message to the hub using the action method , but my question is slightly different:

I am on version 0.5.2 of signalr using hubs. In older versions, you were asked to create methods on the hub to send messages to all clients, which I have:

public class MyHub : Hub { public void SendMessage(string message) { // Any other logic here Clients.messageRecieved(message); } ... } 

So, in 0.5.2 I want to send a message to all clients (say, from somewhere in the controller). How to access an instance of MyHub ?

The only way I referenced is:

 var hubContext = GlobalHost.ConnectionManager.GetHubContext<MyHub>(); hubContext.Clients.messageRecieved("hello"); 

This is fine, but I want to call a method on my hub.

+6
source share
2 answers

You can do this using the static method:

SignalR v.04 -

 public class MyHub : Hub { internal static void SendMessage(string message) { var connectionManager = (IConnectionManager)AspNetHost.DependencyResolver.GetService(typeof(IConnectionManager)); dynamic allClients = connectionManager.GetClients<MyHub>(); allClients.messageRecieved(message); } ... } 

Signal R 0.5 +

 public class MyHub : Hub { internal static void SendMessage(string message) { IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MyHub>(); context.Clients.messageRecieved(message); } ... } 

Then you can call it like this:

 MyHub.SendMessage("The Message!"); 

Good article on SignalR API: http://weblogs.asp.net/davidfowler/archive/2012/05/04/api-improvements-made-in-signalr-0-5.aspx

Courtesy of Paolo Moretti in the comments

+18
source

I had the same problem, in my example addNotification is a client method:

 var hubContext = GlobalHost.ConnectionManager.GetHubContext<SignalR.NotificationsHub>(); hubContext.Clients.addNotification("Text here"); 

On the client side, you can add code to call the hub method in addNotification:

 var notification = $.connection.notificationHub; notification.addNotification = function (message) { notification.addServerNotification(message); // Server Side method } $.connection.hub.start(); 

Hub:

  [HubName("notificationHub")] public class NotificationsHub : Hub { public void addServerNotification(string message) { //do your thing } } 

UPDATE: I read your question over and over again, I really cannot find a reason for this. As a rule, hub methods are called from the client side, or I misunderstood you, one way or another, this update. If you want to do a server thing, then notify clients.

  [HttpPost] [Authorize] public ActionResult Add(Item item) { MyHubMethodCopy(item); var hubContext = GlobalHost.ConnectionManager.GetHubContext<SignalR.NotificationsHub>(); hubContext.Clients.addNotification("Items were added"); } private void MyHubMethodCopy(Item item) { itemService.AddItem(item); } 
+4
source

Source: https://habr.com/ru/post/920425/


All Articles