32
votes

I am using signalr and asp.net MVC3 to build a sample chat application. Here is what my signalr hub looks like

public class MyHub:Hub,IDisconnect
{
 public Task Join()
 {
  string username = HttpContext.Current.User.Identity.Name;
  //find group based on username
  string group = getGroup(username)
  return Groups.Add(Context.ConnectionId, group);
 }

 public void doStuff()
 {
  string group = getGroup();
  Clients[group].doStuffOnBrowser();
 }
}

My problem is that my app crashed when the page loads. on stepping through with the debugger, I found that HttpContext.Current.User.Identity.Name is null even though the user has already been authenticated. How can I get the username in my Task Join() method?

1
Which authentication mode do you use (forms, windows, etc.)? Are you sure that the user is authenticated? Because in a new intranet mvc3 app both the HttpContext.Current.User and Context.User aren't null and containing the current user. - nemesv
@nemesv - My application uses forms authentication and is a internet application. The page that uses signalr can be accessed only if the user is authenticated - user1625066
Hello @user1, can you provide me a demo for multiple chat rooms using signalR. I want to implement chat server like chat.stackoverflow.com - Mohd Aman
my email id is: [email protected]. if u have any demo please send me. - Mohd Aman

1 Answers

32
votes

When using SignalR hubs you can use the HubCallerContext.User property to:

Gets the user that was part of the initial http request.

So try it with:

public Task Join()
{
    string username = Context.User.Identity.Name;
    //find group based on username
    string group = getGroup(username)
    return Groups.Add(Context.ConnectionId, group);
}