niao
niao

Reputation: 5070

SignalR inside _Layout.cshtml - persist connection

I decided to use SignalR for chat on my page. Chat page is opened when user clicks on "Enter Chat" link which is placed inside _Layout.cshtml. This works fine. However, what I would like to achieve is the following functionality:

I am using the following code to connect to the chat application:

$(function () {
            //declare a proxy to reference the hub
            var chatHub = $.connection.chatHub;
            registerClientMethods(chatHub);
            //Start Hub
            $.connection.hub.start().done(function () {
                registerEvents(chatHub);
                chatHub.server.connect(@User.Identity.Name);


            });
        });

However when I place this code inside my _Layout.cshtml page, users are permanently logged off and connected again each time they navigate through pages (they are intended to be opened inside _Layout.cshtml). Is there any way for persisting connection with the hub when navigating through page? What is the best practices when using this kind of functionality?

Upvotes: 0

Views: 1085

Answers (1)

N. Taylor Mullen
N. Taylor Mullen

Reputation: 18301

Whenever you navigate away from a page or in any way refresh the contents of the page you will need to start a fresh SignalR connection. There are two ways to handle this behavior when navigating through pages:

  1. Create a single page application.
  2. Handle users connecting/disconnecting on the server in such a way that they're not truly logged out until they leave the site.

Now to dive into a little more detail on #2. Users on your site may disconnect/connect every time they transition to a new page but you can control how they log out or appear disconnected via your server side logic. You can get this functionality by keeping a set of "online" users in your server side code and then only considering them offline after a specified timeout value.

Upvotes: 3

Related Questions