1

I see several examples such as this where the messages are sent from a hub using javascript. How can I send a message over this same connection from my c# code?

Specifically, I hit a post method in my web api controller and I would like to send a message over the SignalR connection from this controller. Is this possible?

public class ChatHub : Hub
{
    public void Send(string name, string message)
    {
        // Call the addNewMessageToPage method to update clients.
        Clients.All.addNewMessageToPage(name, message);
    }
}

and then in my Web Api post method:

  ChatHub hub = new ChatHub();
  hub.Send("testName", "test message");

All the examples I have seen send these messages from the javascript. This is my first time using SignalR. Can I send a message from the web api controller like this?

Thank you very much for your time. Please let me know if I am being unclear or if you need any more information from me.

user95227
  • 1,853
  • 2
  • 18
  • 36

1 Answers1

4

Assuming your hub is located in your webapi:

var hubContext = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
hubContext.Clients.All.send("name", "message");

See also calling SignalR hub from WebAPI controller issues

Community
  • 1
  • 1
Tom B.
  • 2,892
  • 3
  • 13
  • 34
  • what if hub is different app, I got two apis, once of them starts hub and when I call a method in other api, would like to send message to all subscriber of the hub started by first api. – Bhavesh Aug 17 '18 at 03:32