SignalR - Set ClientID Manually

折月煮酒 提交于 2019-12-20 09:53:55

问题


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 specific user at the start of the session - say a GUID Primary Key for the user?


回答1:


Replace the IConnectionIdFactory with your own https://github.com/SignalR/SignalR/wiki/Extensibility.

Sample usage: http://www.kevgriffin.com/maintaining-signalr-connectionids-across-page-instances/

EDIT: This is no longer supported in the latest versions of SignalR. But you can define a user id for a specific connection using the new IUserIdProvider




回答2:


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.




回答3:


The SignalR Client Side documentation outlines the following:

connection.id - Gets or sets the client id for the current connection

This certainly indicates that one should be able to set the clientID client side, without all the above plumbing. Is this not working? If working, how would this line of code look like?



来源:https://stackoverflow.com/questions/9606569/signalr-set-clientid-manually

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!