Pregunta

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?

¿Fue útil?

Solución

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);
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top