I am trying to use the Caller method outside my Hub Context. I have a helper class which works fine when broadcasting a message to all users like so:
hub.Clients.All.newLessonAlert(notif);
It won't allow me to use the Caller method within this class but this works fine in the hub context class. Why is this? I have also tried to move all of my functions inside the context class but I now get this unhanded exception:
Using a Hub instance not created by the HubPipeline is unsupported
Is there a straightforward way to continue to use my helper class and identify connections to the hub?
I solved this in the following way:
I created a OnConnected
method in my Hub class. This assigned the currently connected user to a group.
[HubName("NotificationsHub")]
public class NotificationHub : Hub
{
private static IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
public override Task OnConnected()
{
string userid = Context.Request.User.Identity.GetUserId();
Groups.Add(Context.ConnectionId, userid);
return base.OnConnected();
}
}
Modified my HubHelper
class to now broadcast this alert to the currently connected user (specified by the user's ID)
public void HighScoreAlert(int gameid, int score, string userID)
{
string message = "High Score achieved on " + gameid;
hub.Clients.Group(userID).score(message);
}
For the controller action I pass in the user's ID and then call the HubHelper method featured above.
Hope this helps someone