Search code examples
asp.netsignalrsignalr-hub

SignalRv2 - Passing values to Hub


Ill try my best to explain this. In my Hub code, i have instantiated the ConnectionMapping class. It was taken from here http://www.asp.net/signalr/overview/guide-to-the-api/mapping-users-to-connections#inmemory .

This ConnectionMapping requires a unique key for its dictionary. I have a webform code-behind called default.aspx.cs. In this code behind, I will get a unique Login Username inside the Page_Load event. How do i pass this username to the Hub to add it to the ConnectionMapping?

I tried.

IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<MyHub>();

But i dont know what im doing after doing this. Help.


Solution

  • The short answer is, you don't. Not with the code you have. The issue is this sequence:

    • Client requests page
    • Server-side code runs (Page_Load)
    • Resulting HTML/JS is sent to client
    • Client connects to SignalR

    At this point, you would presumably add to the ConnectionMapping. The issue being of course, that any data/variables in Page_Load are no longer available, and you'd have no way of mapping the connection you just received to that page request even if they were.

    Your website needs to hold on to some piece of information, perhaps that username, and pass it to the hub on connection (possibly via the query string). The data could even be stored in the page as part of the Page_Load event (in a hidden div or through some other mechanism).

    Now you have both pieces of information at the same time, and can add to the mapping normally.