Search code examples
asp.net-mvc-5signalr

Signalr Context null When Calling from Class


I've set up Signalr on my MVC 5 website, and most of it is working fine. For example, if I try and send a test message using Javascript like so it works great:

$.connection.hub.start().done(function () {
    chat.server.send("Username", "This is a test message");
}); 

And my C# send method in the Hub sends the message like so:

 public void Send(string username, string message)
 {
     string name = Context.User.Identity.Name;
     Clients.Group(username).getMessages("From: " + name + " - " + message);
 }

The problem arises when i try to call the Send method via C#, like this:

ChatHub ch = new ChatHub();
ch.Send("Username", "This is a test message");

When it hits the method during debugging, the Context object is null and it fails.

Essentially, a user sends a message in the View, it hits a controller method, this method calls a notification method in a separate helper class, and this separate class calls the Send method of my Signalr Hub.

Would I need to get the context in the controller, and pass it to the helper class, and then to the Hub? Or is there a better, alternative approach?

Thanks.

UPDATE I did manage to get the username using:

  string name = System.Web.HttpContext.Current.User.Identity.Name;

However, even if I do this, it now throws an exception when it hits this line:

Clients.Group(username).getMessages("From: " + name + " - " + message);

So i think there's a context issue when calling Send from C# only (not from Javascript)


Solution

  • So it turns out from reading this: https://stackoverflow.com/a/36988086/4181058

    "If you want to send messages to clients from your own code that runs outside the Hub class, you can't do it by instantiating a Hub class instance, but you can do it by getting a reference to the SignalR context object for your Hub class."

    So my solution instead of this:

    ChatHub ch = new ChatHub();
    ch.Send("Username", "This is a test message");
    

    Was this:

    var context = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
    context.Clients.Group(username).getMessages("From: " + name + " - " + message);