I am using the hub- feature of SignalR (https://github.com/SignalR/SignalR) to publish messages to all subscribed clients:
public class NewsFeedHub : Hub
public void Send(string channel, string content)
{
Clients[channel].addMessage(content);
}
This works fine when calling "Send" via Javascript, but I would also like the web application to publish messages (from within an ASP.NET MVC action method). I already tried instantiating a new object ob NewsFeedHub and calling the Send method, but this results in an error (as the underlying "Connection" of the Hub is not set). Is there a way to use the Hub without a connection?
Please note that the SignalR API has changed multiple times since this question was asked. There is a chance that some answers will become out of date. This does not mean that they should be down-voted as they were correct at the time of writing
There is another updated answer for this, as seen in the SignalR Wiki
c#
vb.net
Update
This code has been updated. Follow http://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-server for changes.
If you are using DI container
If you are using a DI container to wire up your hubs, get
IConnectionManager
from your container, and callGetHubContext
on that connectionManager.Following on from DDan's answer you can create an overloaded static method and keep common logic in one method - I use this pattern
Then from your controller you can use
updated: This answer is old, too! SignalR's public API is in constant flux, it seems. Tim B James has the new, proper API usage as of July 2012.
The currently accepted answer from Mike is old, and no longer works with the latest version of SignalR.
Here's an updated version that shows how to post a message to a hub from an MVC controller action:
2018 February, Short and simple solution
For solving this I usually design my hubs in the following way:
So it's easy to call from Javascript and from back-end code as well. The two methods are resulting in the same event at the client.