无法使用 SignalR 向特定用户发送消息

Mat*_*ier 3 c# asp.net-mvc signalr

我无法使消息从后面的代码发送给一个特定用户。Clients.All有效,Clients.AllExcept(userId)有效,但无效Client.User(userId)

我的中心:

public class MessagingHub : Hub
{
    public override Task OnConnected()
    {
        var signalRConnectionId = Context.ConnectionId;
        // for testing purpose, I collect the userId from the VS Debug window
        System.Diagnostics.Debug.WriteLine("OnConnected --> " + signalRConnectionId);
        return base.OnConnected();
    }
}
Run Code Online (Sandbox Code Playgroud)

我的控制器从后面的代码发送消息:

public void PostMessageToUser(string ConnectionId)
{
    var mappingHub = GlobalHost.ConnectionManager.GetHubContext<MessagingHub>();

    // doesn't works
    mappingHub.Clients.User(ConnectionId).onMessageRecorded();

    // doesn't works
    mappingHub.Clients.Users(new List<string>() { ConnectionId }).onMessageRecorded();

    // works
    mappingHub.Clients.All.onMessageRecorded();

    // works (?!)
    mappingHub.Clients.AllExcept(ConnectionId).onMessageRecorded();

}
Run Code Online (Sandbox Code Playgroud)

我的集线器是如何在 JS 上初始化的:

var con, hub;
function StartRealtimeMessaging()
{
    con = $.hubConnection();
    hub = con.createHubProxy('MessagingHub');

    hub.on('onMessageRecorded', function () {
        $(".MessageContainer").append("<div>I've received a message!!</div>");
    });
    con.start();
}
Run Code Online (Sandbox Code Playgroud)

最后,我如何向集线器发送一条(n 空)消息:

function TestSendToUser(connectionId)
{
    $.ajax({
        url: '/Default/PostMessageToUser',
        type: "POST",
        data: { ConnectionId: connectionId},// contains the user I want to send the message to
    });
}
Run Code Online (Sandbox Code Playgroud)

因此,它可以与 or 完美配合mappingHub.Clients.All.onMessageRecorded();,但不能与mappingHub.Clients.User(ConnectionId).onMessageRecorded();或 配合使用mappingHub.Clients.Users(new List<string>() { ConnectionId}).onMessageRecorded();

有趣的是,它适用于mappingHub.Clients.AllExcept(ConnectionId).onMessageRecorded();:除了给定的用户 ID 之外,所有连接的用户都会收到消息,这意味着用户 ID 是好的,并且用户可以很好地识别。那么,为什么Clients.User(ConnectionId)不起作用呢?

Mat*_*ier 5

如果您想向一个特定连接发送消息,并且当您想使用 时ConnectionId,请确保使用Clients.Client, 而不是Clients.User

像这样:

public void PostMessageToUser(string connectionId)
{
    var mappingHub = GlobalHost.ConnectionManager.GetHubContext<MessagingHub>();

    // Like this
    mappingHub.Clients.Client(connectionId).onMessageRecorded();

    // or this
    mappingHub.Clients.Clients(new List<string>() { connectionId }).onMessageRecorded();
}
Run Code Online (Sandbox Code Playgroud)