【发布时间】:2014-06-21 05:50:54
【问题描述】:
我正在尝试使用 SignalR 集线器中的以下服务器代码获取已连接用户的列表。对于存储内存数据,我使用以下类:
public class UserInfo
{
public string ConnectionId { get; set; }
public string UserName { get; set; }
public string Role { get; set; }
}
当用户连接时,我将用户添加到连接用户列表中:
public override Task OnConnected()
{
if (Context.User.Identity.IsAuthenticated)
{
if (Context.User.IsInRole("User"))
{
ui.Add(new UserInfo { ConnectionId = Context.ConnectionId, UserName = Context.User.Identity.Name, Role = "User" });
}
else
{
ui.Add(new UserInfo { ConnectionId = Context.ConnectionId, UserName = Context.User.Identity.Name, Role = "Operator" });
}
}
return base.OnConnected();
}
这是我获取当前连接用户列表的方式:
public IEnumerable<UserInfo> GetUsers()
{
var x = (from a in ui where a.Role == "User" select new UserInfo { UserName = a.UserName, ConnectionId = a.ConnectionId }).ToList();
return x;
}
public IEnumerable<UserInfo> GetOperators()
{
var y = (from a in ui where a.Role == "Operator" select new UserInfo { UserName = a.UserName, ConnectionId = a.ConnectionId }).ToList();
return y;
}
不幸的是,公共方法 GetOperators/GetUsers 无法访问,我没有在客户端收到数据:
$(function () {
// Declare a proxy to reference the hub.
var chat = $.connection.chatHub;
//Here I'm calling hub public methods
chat.getOperators = function (data) {
alert(data);
};
chat.getUsers = function (data) {
alert(data);
};
// Create a function that the hub can call to broadcast messages.
chat.client.addChatMessage = function (name, message) {
// Html encode display name and message.
var encodedName = $('<div />').text(name).html();
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#discussion').append('<li><strong>' + encodedName
+ '</strong>: ' + encodedMsg + '</li>');
};
// Get the user name and store it to prepend to messages.
$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.sendChatMessage($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
【问题讨论】:
-
你在哪里调用服务器方法 GetUsers / GetOperators?
-
我确实更新了JS部分,你可以在那里看到评论。
标签: signalr signalr-hub