4

I need to pass User.Identity.Name to Windows Form client.

Method

public override Task OnConnected() {

    string userName = Context.User.Identity.Name;
    string connectionId = Context.ConnectionId;

    var user = Users.GetOrAdd(userName, _ => new User {
        Name = userName,
        ConnectionIds = new HashSet<string>()
    });

    lock (user.ConnectionIds) {
        user.ConnectionIds.Add(connectionId);
        if (user.ConnectionIds.Count == 1) {
            Clients.Others.userConnected(userName);
        }
    }
    return base.OnConnected();
}

But Context.User.Identity.Name is null? Why? How to solve it?

scniro
  • 16,844
  • 8
  • 62
  • 106
Dmitry Kazakov
  • 1,639
  • 3
  • 27
  • 47
  • Maybe you're running into the same issue described here: http://stackoverflow.com/questions/22002092/context-user-identity-name-is-null-with-signalr-2-0-2-how-to-fix-it Basically, you have to call app.MapSignalR *after* you setup your authentication. – halter73 Mar 07 '14 at 00:32
  • http://stackoverflow.com/questions/35794541/how-assign-a-connectionid-to-username-which-is-send-from-client-to-server-in-sig – Khalid Mar 04 '16 at 11:37

1 Answers1

8

It looks like you are trying to get the username when connecting to the hub. I solved a similar issue by passing the username from my client. It also sounds like you are making use of the SignalR .NET client. Give this a try

Client

Connection = new HubConnection("http://.../", new Dictionary<string, string>
{
    { "UserName", WindowsIdentity.GetCurrent().Name }
});

Hub

public override Task OnConnected()
{
    string userName = Context.QueryString["UserName"]
}
scniro
  • 16,844
  • 8
  • 62
  • 106
  • 1
    I'm having trouble with [Context.User.Name being empty](http://stackoverflow.com/questions/34709307/signalr-context-user-name-returns-empty) in my hub, it's a massive fudge, but I managed to get my server side code working by passing the username via your method. Thanks! – KidCode Jan 13 '16 at 21:13