我对signalR有些问题,我无法向特定的User From Hub发送消息。
我想这样做:
public void Send(string userToId, string userForId, string message)
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<ChatHubs>();
//userForId - it is Session["UserId"]
context.Clients.User(userForId).updateMessages(message);
}
我已经阅读了这个主题:http://www.asp.net/signalr/overview/guide-to-the-api/mapping-users-to-connections,但我不清楚,因为我没有这个var name = Context.User.Identity.Name;
我在会话变量中有用户信息,第二次我得到如下的connectionId:{当我刷新页面或单击项目中的另一个菜单时,{1}} connectionId已更改。
我有一些问题: 1)我可以在没有connectionId的情况下向特定用户发送消息(仅使用session [“UserId”])吗? 2)总的来说,如何使用SignalR轻松实现一对一的消息传递?
P.S。我正在使用ASP.NET MVC(C#)
答案 0 :(得分:7)
您可以向没有连接ID的所有用户发送广播消息。您只需要为每个用户分配一个唯一ID,并将其作为消息参数发送。
SignalR为每个客户端提供唯一ID作为连接ID。您可以使用该连接ID,也可以在创建客户端时为客户端分配唯一ID,并将其用作连接ID。这取决于你想要使用的东西。
修改强>
只需在Hub类文件中更新您的方法.....
public void Send(string name, string message, string connectionid)
{
// Call the addNewMessageToPage method to update clients.
Clients.All.addNewMessageToPage(name, message, connectionid);
}
在您的客户端您可以在包含SignalR文件后更新添加代码: -
var chat = $.connection.chatHub;
chat.client.addNewMessageToPage = function (name, message, connectionid) {
if (connectionid == $('#connection').val()) {
// Do What You want Here...
};
};
// Get the user name and store it to prepend to messages.
$('#displayname').val(prompt('Enter your name:', ''));
$('#connection').val(prompt('Enter your ID:', ''));
// 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.send($('#displayname').val(), $('#message').val(), $('#connection').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
希望这有助于......
答案 1 :(得分:3)
如果您想在SignalR中向特定用户发送消息,最简单的方法是使用表单身份验证。您还可以使用自定义会话进行表单身份验证。创建后,您的会话代码就会生成此代码。
FormsAuthentication.SetAuthCookie(username.Trim(), false);
然后在signalR中,您可以使用此行向该用户发送消息:
var username = Context.User.Identity.Name;
context.Clients.User(username).updateMessages(message);
修改强>
对于您的问题,将用户名传递给此方法(接收者用户名)并将消息推送给该用户。然后您不需要提供userForId,因为您已经拥有发件人用户名&#34; var username = Context.User.Identity .Name;&#34;。此方法只会推送到接收者用户名的方法。如果您还希望向发件人发送消息,您需要使用&#34;来电者&#34;并且你需要一个新的函数来获取javascript中的调用者消息。我希望它对你有用。
public void Send(string username, string message)
{
context.Clients.Caller.updateMessagesCaller(message);
context.Clients.User(username).updateMessages(message);
}
这条消息只会是那个用户名。我的建议是在整个项目中使用FormAuthentication实现。谢谢。