SignalR and HttpContext/Session

Lodewijk picture Lodewijk · Sep 18, 2012 · Viewed 20.4k times · Source

I understand why SignalR doesn't give you access to the HttpContext. However, this is quite problematic for us. Let me explain:

Our application is a Multi-Tenant application where the user chooses the environment while logging in. This basically registers the ConnectionStringName in the HttpSession. In our SignalR Hub, we need to access the database on Disconnect. But this is not possible because we have no HttpContext at this point and cannot determine the environment to write to.

Can anyone provide us with a suggestion how to solve this problem? We're a bit stuck on this one.

EDIT: Bonus point if your solution works in a Load-Balanced environment.

Answer

Raciel R. picture Raciel R. · Aug 29, 2013

This is an old question, but I'm leaving my answer just in case it is helpful to anyone out there.

Since your hub extends Microsoft.AspNet.SignalR.Hub it has access to the Context property of type HubCallerContext

This property exposes a lot of information from the caller:

  • ConnectionId
  • Headers
  • QueryString
  • Request
  • Cookies
  • User

In my solution I use the username stored in Context.User.Identity.Name as a key in my key/value store (Redis in my case) to keep track of all the connections a user has.

You can override OnConnnect and OnDisconnect to maintain the list of connections associated to the user. You can also store anything else you want along with the connections ids (your user connection strings, in your case).