SignalR - Set ClientID Manually

前端 未结 3 906
萌比男神i
萌比男神i 2021-02-02 13:27

I want to be able to have individual users send messages to each other using SignalR, therefore I need to send to a Specific Client ID. How can I define the client ID for a spec

3条回答
  •  执笔经年
    2021-02-02 14:09

    In SignalR version 1, using the Hubs approach, I override the Hub OnConnected() method and save an association of a .NET membership userId with the current connection id (Context.ConnectionId) in a SQL database.

    Then I override the Hub OnDisconnected() method and delete the association between the .NET membership userId and the current connection id. This means, on a page reload, the userId/connectionId association will be up-to-date.

    Something along the lines of:

    public class MyHub : Hub
    {
        private MembershipUser _user
        {
            get { return Membership.GetUser(); }
        }
    
        private Guid _userId
        {
            get { return (Guid) _user.ProviderUserKey; }
        }
        
        private Guid _connectionId
        {
            get { return Guid.Parse(Context.ConnectionId); }
        }
    
        public override Task OnConnected()
        {
            var userConnectionRepository = new UserConnectionRepository();
            userConnectionRepository.Create(_userId, _connectionId);
            userConnectionRepository.Submit();
    
            return base.OnConnected();
        }
    
        public override Task OnDisconnected()
        {
            var userConnectionRepository = new UserConnectionRepository();
            userConnectionRepository.Delete(_userId, _connectionId);
            userConnectionRepository.Submit();
    
            return base.OnDisconnected();
        }
    }
    

    Then when I need to trigger a SignalR event for a specific user, I can work out the connectionId from the database association(s) with the current userId - there may be more than one association if multiple browser instances are involved.

提交回复
热议问题