SignalR and HttpContext/Session
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).
Hi had a similar problem as I needed to identify non-authenticated visitors to my application to personalise their requests to the SignalR hub.
I have solved it by accessing "HttpContext.Current.Request.AnonymousId". The AnonymousId maps to a temporary record in a self-implemented Session-entity in a SQL database - essentially emulating a database-backed session.
Here some relevant documentation in case you wish to customize the AnonymousId, or initialise the database-entry: http://msdn.microsoft.com/en-us/library/system.web.httprequest.anonymousid.aspx
Moreover, you should be able to access the Context in OnDisconnected() like this: Context.Request.GetHttpContext().
I hope this helps.
If you're using ASP.NET Core SignalR 3.0 (not ASP.NET SignalR 2.1) then you can use Context.GetHttpContext()
into get the HttpContext
.
FYI, Signalr 3.0 no longer has the Context.Request
object. The Request context can be reached by accessing the IHttpContextFeature in Context.Features[]
. I used the following:
IHttpContextFeature hcf = (IHttpContextFeature)this.Context.Features[typeof(IHttpContextFeature)];HttpContext hc = hcf.HttpContext;string myCookieValue = hc.Request.Cookies["Value"];
This could probably use some null checks or could be cleaner, but hopefully this saves someone some time.