Send signalr message from server to all clients

You can do this by using a 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);
    }

    ...
}

SignalR 0.5+

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

    ...
}

You can then call this like so:

MyHub.SendMessage("The Message!");

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

Provided by Paolo Moretti in comments


I had same problem, in my example addNotification is client-side method:

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

On you client side you can add code to call your 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: Reading your question over and over agian I really don't find a reason to do that. Hub methods are usually there to be called from client side, or I misunderstood you, anyway here is an update. If you want to do a server side thing and 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);
  }