Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

To set the right context, let me explain the problem. Till RC1, we used to implement GenerateConnectionIdPrefix() to prefix user Id to the connection Id. Then we could retrieve user id from the connection string anytime we need.

With RC2, we now cannot inherit IConnectionIdPrefixGenerator & implement GenerateConnectionIdPrefix anymore. So I was wondering what are other avenues available to set any property on the hub with our data, that persists throughout the lifetime of the connection.

Going through documentation, I realized setting query strings is one way, but that would mean we need to set it for every call. Setting a round trip state might be another option, but it looks like even that is persistent for a single round-trip and not entire lifetime.

So my end goal is set to property once at start on SignalR connection that can be used throughout the connection lifetime.

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

[Update] As suggested below, I tried to set a state Clients.Caller.Userid in the OnConnected method, then tried to access it in the subsequent call, I found that its null. Both calls are from same connection Id.

like image 324
Gourav Das Avatar asked Jan 14 '23 09:01

Gourav Das


1 Answers

Look at the "Round-tripping state between client and server" section on https://github.com/SignalR/SignalR/wiki/Hubs.

Basically you can read and write from dynamic properties on Clients.Caller in Hub methods such as OnConnected or anything invoked by a client. Ex:

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;

            // ...
        }
    }
}

State that is stored this way will be persisted for the lifetime of the connection.

If you want to learn how to access this state using the SignalR JS client look at the "Round-tripping state" section of https://github.com/SignalR/SignalR/wiki/SignalR-JS-Client-Hubs.

There are other ways to keep track of users without IConnectionIdPrefixGenerator discussed in the following SO answer: SignalR 1.0 beta connection factory

like image 173
halter73 Avatar answered May 17 '23 08:05

halter73