0
votes

I am trying to implement a chat application. Users should be able to send messages to specific users. In order to do that I need to map usernames to their connectionIDs.

My client is using custom authentication. Username is stored in Session["User"]. Therefore I don't have the username stored in Context.User.Identity.Name, which is where SignalR normally takes the username from.

How else can I get the username of the logged in user so that I can map it to Context.ConnectionID?

Here is some sample implementation of public class ChatHub : Hub I found on the web.

private readonly static ConnectionMapping<string> _connections =
        new ConnectionMapping<string>();

    public void SendChatMessage(string who, string message)
    {
        string name = Context.User.Identity.Name;

        foreach (var connectionId in _connections.GetConnections(who))
        {
            Clients.Client(connectionId).addChatMessage(name + ": " + message);
        }
    }

    public override Task OnConnected()
    {
        string name = Context.User.Identity.Name;

        _connections.Add(name, Context.ConnectionId);

        return base.OnConnected();
    }
1

1 Answers

3
votes

Pass your username using query string.

Client

First set query string

For auto generated proxy

$.connection.hub.qs = { 'username' : 'anik' };

For manual proxy

var connection = $.hubConnection();
connection.qs = { 'username' : 'anik' };

then start hub connection

Server

public override Task OnConnected()
{
    var username= Context.QueryString['username'];
    return base.OnConnected();
}