SignalR 用户未在 Client.Users 中注册

SignalR user is not registered in Client.Users

我正在创建 2 个用户之间的聊天。 这是我的集线器和集线器客户端:

public class ConversationHub : Hub<IConversationHubClient>
{
    public override Task OnConnected()
    {
        var id = this.Context.User.Identity.GetUserId();
        //when I breakpoint here, I can see the id of my connected user.
        return base.OnConnected();
    }
}

public interface IConversationHubClient
{
    void MessageReceived(string conversationId, 
        string userId, 
        string text, 
        DateTime date, 
        bool isUser);
}

我从 mvc 控制器调用:

string userId = this.User.Identity.GetUserId();
_conversationHub.Clients
            .User(userId)
            .MessageReceived(model.ConversationId, userId , model.Text, model.Date, true);
//I want to send back the message to the user, for testing purposes

最后是前端:

var conversationhub = $.connection.conversationHub;

//messageReceived
conversationhub.client.MessageReceived = function (conversationId, userId, text, sentOn, isUser){
        alert(':D');
    };

我希望在触发我的 mvc 控制器方法时看到警报,但没有任何反应。在我看来,用户没有在连接的用户中注册,但我不明白为什么以及如何注册它。有人可以帮我吗?

User.Identity.GetUserId()不等于Context.ConnectionId,这是你需要调用特定的客户端。它标识 SignalR 连接。 您需要将用户映射到连接。我建议你看看 this 教程:

好吧,由于我在我的 MVC 控制器上注入 hubContext 的方式,事实证明它不起作用。

我关注了 SignalR DI with ninject 上的文章。

我的绑定有误。按照示例进行操作后,我将绑定更改为:

   this.Kernel.Bind<IHubContext<IConversationHubClient>>()
            .ToMethod(x => GlobalHost.DependencyResolver.Resolve<IConnectionManager>()
               .GetHubContext<ConversationHub, IConversationHubClient>());

一切正常!