代码之家  ›  专栏  ›  技术社区  ›  ExternalUse

.Net Core信号器:从IHubContext(注入控制器)发送给除调用方之外的用户

  •  1
  • ExternalUse  · 技术社区  · 7 年前

    为了仅在控制器中使用注入的IHubContext时识别当前用户,我存储了一个具有用户id的组。 然而,我很难发送给其他人,因为我无法找到一种方法来找出要排除的连接ID。

    我的中心

    public override Task OnConnectedAsync()
    {
    
        Groups.AddAsync(Context.ConnectionId, Context.User.Identity.Name);  
        return base.OnConnectedAsync();
    }
    

    在我的控制器方法中,我可以为该用户调用方法:

    await _signalRHub.Clients.Group(User.Identity.Name).InvokeAsync("Send", User.Identity.Name + ": Message for you");
    

    IHubContext。客户。AllExcept需要连接ID列表。我如何获取已识别用户的连接ID,以便只通知其他用户?

    2 回复  |  直到 7 年前
        1
  •  1
  •   ExternalUse    7 年前

    正如@Pawel所建议的,我现在正在对客户端进行重复数据消除,这很有效(好的,只要您的所有客户端都经过身份验证)。

    private async Task Identification() => await Clients.Group(Context.User.Identity.Name).InvokeAsync("Identification", Context.User.Identity.Name);
    public override async Task OnConnectedAsync()
    {    
        await Groups.AddAsync(Context.ConnectionId, Context.User.Identity.Name);            
        await base.OnConnectedAsync();
        await Identification();
    }
    

    var connection = new signalR.HubConnection("/theHub");            
    var myIdentification;
    connection.on("Identification", userId => {
        myIdentification = userId;
    });
    

    现在你可以测试 callerIdentification == myIdentification 其他方法,如 connection.on("something", callerIdentification)

    @测试人员的评论让我对通过IHubContext发送时有更好的方式充满希望。

        2
  •  0
  •   akraines    2 年前

    在信号器核心中,连接ID存储在信号器连接中。假设您有如下定义的signalrR连接

    signalrConnection = new HubConnectionBuilder()
    .withUrl('/api/apphub')
    ...
    .build();
    

    无论何时发出提取请求,都要添加信号器连接ID作为标头。如。

            response = await fetch(url, {
            ...
            headers: {
                'x-signalr-connection': signalrConnection.connectionId,
            },
        });
    

    然后,在您的控制器中或任何可以访问httpContextAccessor的地方,您可以使用以下内容来排除标头中引用的连接:

        public async Task NotifyUnitSubscribersExceptCaller()
    {
        //Grab callers connectionId
        var connectionId = _httpContextAccessor.HttpContext?.Request.Headers["x-signalr-connection"] ?? "";
        await _hub.Clients.GroupExcept("myGroup", connectionId).SendCoreAsync("Sample", new object[] { "Hello World!" });
    }