Is there a way to set any property on the hub that persists for the lifetime of the connection?

To establish the correct context, let me explain the problem. Prior to RC1, we used a user id prefix for the connection id to implement GenerateConnectionIdPrefix (). Then we could get the user id from the connection string at any time.

With RC2, we can no longer inherit IConnectionIdPrefixGenerator and no longer implement GenerateConnectionIdPrefix. So I was wondering what other options are available for setting any property in the hub with our data persisting throughout the connection time.

Looking through the documentation, I realized that setting query strings is one way, but that means we need to set it for every call. The round trip state setting may be different, but it appears to be a constant value for one round and not for the whole lifetime.

So my end goal is set to a property once when run on a SignalR connection, which can be used for the duration of the connection.

If nothing is currently available, are there any plans to add support to achieve something similar in the next version?

[Update] As suggested below, I tried to set the Clients.Caller.Userid state in the OnConnected method, and then tried to access it on a subsequent call, I found it was null. Both calls refer to the same connection ID.

+3


source to share


1 answer


Have a look at the section "Round trip between client and server" at https://github.com/SignalR/SignalR/wiki/Hubs .

Basically you can read and write from dynamic properties on Clients.Caller

in hub methods like OnConnected

or anything called by the client. Example:

using System;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR;

namespace StateDemo
{
    public class MyHub : Hub
    {
        public override Task OnConnected()
        {
            Clients.Caller.UserId = Context.User.Identity.Name;
            Clients.Caller.initialized();
            return base.OnConnected();
        }

        public void Send(string data)
        {
            // Access the id property set from the client.
            string id = Clients.Caller.UserId;

            // ...
        }
    }
}

      



The state that is stored this way will persist for the lifetime of the connection.

If you want to know how to access this state using the SignalR JS client, take a look at the Round Disconnect section of https://github.com/SignalR/SignalR/wiki/SignalR-JS-Client-Hubs .

There are other ways to track users without IConnectionIdPrefixGenerator

, discussed in the following SO answer: SignalR 1.0 factory beta connection

+7


source







All Articles