Jerzy Gawor
Jerzy Gawor

Reputation: 151

SignalR Get user Id from controller

I have a question, how can i get userId from Application controller? I saw many samples, how to get it from Hubs. But i don't know how can i call hub from controller in other way then

var context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();

in the context i havent any id.

I saw samples like that, here i can call context and get UserId, but this works only in the Hub.

var name = context.User.Identity.Name;

I know that i can do something like that:

    public class MyHub : Hub
{
    public void Send(string userId, string message)
    {
        Clients.User(userId).send(message);
    }
}

But i have to call hub from the controller.

Thanks for help

Upvotes: 3

Views: 9197

Answers (3)

Jerzy Gawor
Jerzy Gawor

Reputation: 151

i found a solution.

By the way, thanks for your answers.

I try to use signalR from class which was calling by the application controller. In the class i haven't got any context and special data about user who called server.

But i found into the controller info about which user calling the server.

this.User.Identity.Name

Happy coding ;)

Upvotes: 1

rdoubleui
rdoubleui

Reputation: 3598

May I suggest a slightly different approach. In general that poking into the the hub from outside the signalr context doesn't work well or at least makes things more complicated.

You could have the controller act as client to the hub itself and expose the information you need via the hub to the controller. All you'd need is the SignalR Desktop Client package. While it adds an overhead, you'll have a much more compliant way for data retreivement and as a benefit a nice separation of concerns.

Here's a similar question that I replied to. HTH.

Upvotes: 3

radu-matei
radu-matei

Reputation: 3520

If you have some kind of authentication in your application, a good idea might be keeping a mapping between users and connections.

This way, whenever you want to send a message to a user, simply retrieve all that user's connectin IDs and send the message to all of them.

    foreach(var connectionId in UserMapping) 
        context.Clints.Client(connectionId).sendMessage(message);

This way, you are able to send messages to specific clients from outside the hub and you are sure that all instances of the client get notified.

Take a look here for more information on Mapping SignalR Users to Connections.

Hope this helps.

Best of luck!

Upvotes: 2

Related Questions