Eng.Helewa
Eng.Helewa

Reputation: 69

How to get Connection id from user id inside signalr hub

I have a signalr hub with a function like this

public void SendSurveyNote(int surveyId,List<string> users){}

Here I want to add all users of the list into a group "Survey_" + surveyId Then sending the group a message. But I only have the user id but joining a group requires a connection id. So how could I manage that. Also I wonder would it be a performance issue to send each user a message without a group?

I call the function above when I add a new Survey like this

private static HubConnection hubConnection = new HubConnection(ConfigurationManager.AppSettings["BaseUrl"]);
private static IHubProxy hubProxy = hubConnection.CreateHubProxy("myHub");
await hubConnection.Start();
hubProxy.Invoke("SendSurveyNote", model.Id, users);

thanks

Upvotes: 1

Views: 6445

Answers (1)

scniro
scniro

Reputation: 16989

You have access to the connection ID within Context. You'll want to establish groups within OnConnected. Observe the following implementation on your hub, where we will call it MyHub. We'll also group by Context.User.Identity.Name to establish a unique group per user, but this could be any value you wish to group by.

public class MyHub: Hub
{
    public override Task OnConnected()
    {
        Groups.Add(Context.ConnectionId, Context.User.Identity.Name)

        return base.OnConnected();
    }
}

See Working with Groups in SignalR for more information

Upvotes: 4

Related Questions