问题
can i add e.g. username instead of connection.id. does it work? i'm asking this because over ConnectionId i can't send notification to the user, because ConnectionId always is changes?
Groups.Add("my_username", "mygroup1);
回答1:
No you cannot, you must use a ConnectionID. You can however do the following.
On your hub store a list of users mapped to connection IDs:
static ConcurrentDictionary<string, User> _users = new ConcurrentDictionary<string, User>();
Then after a client connection has been started you can call into a method like:
myHub.server.createUser("MyUsername");
Of course on the server you'd have:
public void createUser(string userName)
{
// You'd create a User class that had both of the following properties
var user = new User
{
UserName = userName,
ConnectionID = Context.ConnectionId
};
_users.TryAdd(user.ConnectionID, user);
}
SO whenever you want to lookup a user via connection ID you still have context of his/her username via the _users dictionary.
Note: This code works via signalr 1.0 alpha +
来源:https://stackoverflow.com/questions/13850055/signalr-group-add