SignalR - 将参数发送到OnConnected?

Rob*_*ous 14 signalr signalr-hub

我有以下JS工作:

var chat = $.connection.appHub;
Run Code Online (Sandbox Code Playgroud)

我的应用程序有一个集线器,AppHub可处理两种类型的通知 - ChatOther.我正在使用单个集线器,因为我需要始终访问所有连接.

我需要能够OnConnected通过以下内容告诉它是哪种类型:

[Authorize]
public class AppHub : Hub {
    private readonly static ConnectionMapping<string> _chatConnections =
        new ConnectionMapping<string>();
    private readonly static ConnectionMapping<string> _navbarConnections =
        new ConnectionMapping<string>();
    public override Task OnConnected(bool isChat) { // here
        string user = Context.User.Identity.Name;
        if (isChat){
            _chatConnections.Add(user, Context.ConnectionId);
            _navbarConnections.Add(user, Context.ConnectionId);
        } else{
            _navbarConnections.Add(user, Context.ConnectionId);
        }  
    }
}
Run Code Online (Sandbox Code Playgroud)

用法最好是这样的:

var chat = $.connection.appHub(true);
Run Code Online (Sandbox Code Playgroud)

如何从javascript将该参数传递到集线器?

更新:

发信息:

 // will have another for OtherMessage
 public void SendChatMessage(string who, ChatMessageViewModel message) {
        message.HtmlContent = _compiler.Transform(message.HtmlContent);
        foreach (var connectionId in _chatConnections.GetConnections(who)) {
            Clients.Client(connectionId).addChatMessage(JsonConvert.SerializeObject(message).SanitizeData());
        }
    }
Run Code Online (Sandbox Code Playgroud)

Hal*_*eth 26

我宁愿为您从客户端调用以订阅该类型的集线器添加一个方法.例如

public void Subscribe(bool isChat) {
    string user = Context.User.Identity.Name;
    if (isChat){
        _chatConnections.Add(user, Context.ConnectionId);
    } else{
        _otherConnections.Add(user, Context.ConnectionId);
    }
}
Run Code Online (Sandbox Code Playgroud)

在连接集线器后调用此方法.它的灵活性更加灵活,可以在不必重新连接的情况下更改通知类型.(取消订阅和订阅)

替代

如果你不想要额外的往返/灵活性.您可以在连接到集线器时发送QueryString参数.Stackoverflow回答:Signalr持久连接查询参数.

 $.connection.hub.qs = 'isChat=true';
Run Code Online (Sandbox Code Playgroud)

在OnConnected中:

 var isChat = bool.Parse(Context.QueryString["isChat"]);
Run Code Online (Sandbox Code Playgroud)