I have an MVC project, with multiple pages.
I have a long running process, which updates the client on its progress. However, this update is sent only to a single client, instead of broadcasting to all.
Clients.Client(ConnectionId).sendMessage(msg);
In my layout.cshtml, this is how I connect to the hub
var serverHub = $.connection.notifier;
window.hubReady = $.connection.hub.start(function () { });
The problem is, when I navigate to another page, I no longer receive the messages from signalr, because the connection id has changed.
How should I workaround this issue, such that my signalr hub can still send messages to a single client, while the client navigates from page to page.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You will want to create a server mapping of users to connection id’s. See: SignalR 1.0 beta connection factory.
You will want to let your users persist past an OnDisconnected event and when they connect with a different connection Id you can continue pumping data down to them.
So the thought process could be as follows:
- Page loads, SignalR connection is instantiated
- Once connection is fully started call => TryCreateUser (returns a user, whether it existed or it was created).
- Long Running process Starts
- Client changes pages -> SignalR connection stops
- New Page loads, new SignalR connection is instantiated
- Once connection is fully started see if you have a cookie, session, or some type of data representing who you are => TryCreateUser(userData) (returns the user you created on the last page).
- Data continues pumping down to user.
Note: if you take an authentication approach you will have to be authenticated prior to starting a connection and that data cannot change during the lifetime of a SignalR connection, it can only be created/modified while the connection is in the disconnected state.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0