SignalR cross-domain connection - connecting conne

2019-06-14 02:18发布

问题:

I'm hosting my signalr hub on a separate domain and making cross domain connection to hub from my main application. When a user logs into the main application, signalr connection is established. Now, the problem I'm having is how to identify the connected user inside the hub.

If my Hub was within the main application then I could use the Context.User of the logged in user and maintain a dictionary and update them on Connect and Disconnect events.

But being a cross-domain connection, I don't have the Context.User and no way for me to know to whom that connection ID belongs to. I'm lost here.

What am I missing here?

回答1:

You should keep users credentials and connections ids yourself. You should define List<ClientsEntity> or something like that. Then override onConnected and onDisconnected methods. Client has to send querystring for connecting to your Hub as Lars said.

for example clients send to you like this

$.connection.hub.qs = { 'token' : 'id' };

In the Hub Class:

public class ChatHub : Hub
    {

        static List<ClientsEntity> clientsList = new List<ClientsEntity>();

        public override Task OnConnected()
        {
            string connectionID = Context.ConnectionId;
            string token = Context.QueryString["token"];

            ClientsEntity clientItem = new ClientsEntity();
            clientItem.connectionId = connectionID;
            clientItem.token = token;
            clientItem.connectionTime = DateTime.Now;

            clientsList.Add(clientItem);

            return base.OnConnected();
        }

        public override Task OnDisconnected()
        {
            ClientsEntity item = clientsList.FirstOrDefault(c => c.connectionId == Context.ConnectionId);
            if (item != null) {
                clientsList.Remove(item);
            }

            return base.OnDisconnected();
        }

        public override Task OnReconnected()
        {
            return base.OnReconnected();
        }

        public void Send(string token, string message)
        {
            ClientsEntity user = clientsList.FirstOrDefault(c => c.token == token);

            if (user != null)
                Clients.Client(user.connectionId).sendMessage(token, message);
        }

        public void GetConnectedClients(string token) {
            ClientsEntity user = clientsList.FirstOrDefault(c => c.token == token);

            if(token.Equals("-1") && user != null)
                Clients.Client(user.connectionId).getConnClients(clientsList);
        }

    }


回答2:

You could assign a unique connection token to the user once they log in; then make the client send that in the query string:

$.connection.hub.qs = { 'token' : id };