Avt*_*ili 6 c# asp.net-mvc messaging asp.net-mvc-4 signalr
我有一些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);
}
Run Code Online (Sandbox Code Playgroud)
我已经读过这个话题:http://www.asp.net/signalr/overview/guide-to-the-api/mapping-users-to-connections,但我不清楚,因为我没有这个 var name = Context.User.Identity.Name;我在我获得connectionId时,会话变量中有用户信息,第二个是当我 var myClientId = $.connection.hub.id;刷新页面或单击项目上的另一个菜单时更改了connectionId.
我有一些问题:1)我可以在没有connectionId的情况下向特定用户发送消息(仅使用session ["UserId"])吗?2)总的来说,如何使用SignalR轻松实现一对一的消息传递?
PS我正在使用ASP.NET MVC(C#)
您可以向没有连接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);
}
Run Code Online (Sandbox Code Playgroud)
在您的客户端,您可以在包含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();
});
});
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助...
如果您想在 SignalR 中向特定用户发送消息,最简单的方法是使用表单身份验证。您还可以将自定义会话与表单身份验证一起使用。创建会话代码后立即放置此代码。
FormsAuthentication.SetAuthCookie(username.Trim(), false);
Run Code Online (Sandbox Code Playgroud)
然后在 signalR 中,您可以使用此行向该用户发送消息:
var username = Context.User.Identity.Name;
context.Clients.User(username).updateMessages(message);
Run Code Online (Sandbox Code Playgroud)
编辑:
对于您的问题,将用户名传递给此方法(接收者用户名)并将消息推送给该用户。然后您不需要提供 userForId,因为您已经拥有带有“var username = Context.User.Identity.Name;”的发送者用户名。另外此方法只会推送到接收者用户名的方法。如果您还想向发件人发送消息,您需要使用“Caller”,并且需要编写一个新函数来用 javascript 获取呼叫者消息。我希望您能清楚地了解这一点。
public void Send(string username, string message)
{
context.Clients.Caller.updateMessagesCaller(message);
context.Clients.User(username).updateMessages(message);
}
Run Code Online (Sandbox Code Playgroud)
此消息将仅发送到该用户名。我的建议是在整个项目中使用 FormAuthentication 实现。谢谢。
| 归档时间: |
|
| 查看次数: |
23637 次 |
| 最近记录: |