Pergunta

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?

Foi útil?

Solução

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

Outras dicas

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.

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?

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top