2014-03-07 59 views
2

我需要將User.Identity.Name傳遞給Windows窗體客戶端。爲什麼Context.User.Identity.Name在Windows Form Hub上下文中爲null?

方法

public override Task OnConnected() { 

    string userName = Context.User.Identity.Name; 
    string connectionId = Context.ConnectionId; 

    var user = Users.GetOrAdd(userName, _ => new User { 
     Name = userName, 
     ConnectionIds = new HashSet<string>() 
    }); 

    lock (user.ConnectionIds) { 
     user.ConnectionIds.Add(connectionId); 
     if (user.ConnectionIds.Count == 1) { 
      Clients.Others.userConnected(userName); 
     } 
    } 
    return base.OnConnected(); 
} 

Context.User.Identity.Name爲空?爲什麼?如何解決它?

+0

也許你正在運行到這裏所描述的同樣的問題:http://stackoverflow.com/questions/22002092/context-user-identity-name-is-null-with-signalr-2-0-2-how-to-fix-it基本上,你必須在設置你的認證之後調用app.MapSignalR *。 – halter73

+0

http://stackoverflow.com/questions/35794541/how-assign-a-connectionid-to-username-which-is-send-from-client-to-server-in-sig – Khalid

回答

5

看起來您正在嘗試在連接到集線器時獲取用戶名。我通過從我的客戶端傳遞用戶名解決了類似的問題。這聽起來像你正在使用SignalR .NET客戶端。試試這個

客戶

Connection = new HubConnection("http://.../", new Dictionary<string, string> 
{ 
    { "UserName", WindowsIdentity.GetCurrent().Name } 
}); 

樞紐

public override Task OnConnected() 
{ 
    string userName = Context.QueryString["UserName"] 
} 
+1

我遇到了麻煩[ Context.User.Name是空的](http://stackoverflow.com/questions/34709307/signalr-context-user-name-returns-empty)在我的樞紐,這是一個巨大的詭計,但我設法讓我的服務器端通過您的方法傳遞用戶名的代碼。謝謝! – KidCode

相關問題