signalR – 获取用户名

我正在使用signalr和asp.net MVC3来构建示例聊天应用程序。 这是我的信号器中心的样子

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(); } } 

我的问题是我的应用程序在页面加载时崩溃了。 在使用调试器时,我发现即使用户已经过身份validation,HttpContext.Current.User.Identity.Name仍为null。 如何在Task Join()方法中获取用户名?

使用SignalR集线器时,您可以使用HubCallerContext.User属性:

获取属于初始http请求的用户。

所以试试吧:

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