0

How to use Session in SignalR Hub class? ASP.NET MVC

Here is my code:

public override Task OnConnected()
{
   if (HttpContext.Current.Session["US_ID"] != null)
   {
      lstUsers.Add(Context.ConnectionId, new USER { US_ID = HttpContext.Current.Session["US_ID"].ToString() });
      Clients.All.BroadcastConnections(lstUsers);
   }
   return base.OnConnected();
}

Error: Object reference not set to an instance of an object.

Error in this line if (HttpContext.Current.Session["US_ID"] != null)

How to solve it?

Sophairk
  • 253
  • 3
  • 11
  • [No access to the Session information through SignalR Hub. Is my design is wrong?](https://stackoverflow.com/questions/20522477/no-access-to-the-session-information-through-signalr-hub-is-my-design-is-wrong) as discussed before and mentioned in the [documents](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-3.1#session-state) you can't. – Eldar May 29 '20 at 07:37
  • 1
    I ask for other solutions, because my completed project already use session, I just modify project add signalR. – Sophairk May 29 '20 at 07:41
  • What you can do is setting a cookie before opening hub connection. And read that cookie from Context in hub class. – Eldar May 29 '20 at 08:25
  • Okay thank you, I will try it. – Sophairk May 29 '20 at 09:01
  • 1
    Another option can be to pass it into the hub via querystring. Like so; $.connection.hub.qs = { 'US_ID' : 'test' }; – EddDotNet May 31 '20 at 13:29
  • There is also `Context.User` (`Context.User.Identity.Name`), that can help if you need the currently logged-in user id. – Vasiliy Zverev Jun 17 '23 at 01:42

0 Answers0