signalR - 获取用户名

signalR  - 获取用户名

问题描述:

我使用signalr和asp.net MVC3构建一个示例聊天应用。这里是我的signalr毂看起来像

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

我的问题是我的应用程序崩溃的页面加载时。与调试器逐句通过,我发现HttpContext.Current.User.Identity.Name为空,即使用户已经被认证。我怎样才能得到我的任务的用户名join()方法?

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?

在使用的 SignalR枢纽你可以使用 HubCallerContext.User 属性:

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

获取,这是最初的HTTP请求的一部分用户。

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

因此​​,与试试吧:

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