如何在asp.net核心SignalR中遍历用户? [英] How to iterate over users in asp.net core SignalR?

查看:171
本文介绍了如何在asp.net核心SignalR中遍历用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在.net核心上的SignalR应用程序中,我有一段类似于以下内容的代码:

In a SignalR application on .net core, I have a working piece of code similar to the following:

public Task SendPrivateMessage(string user, string message)
{
    var sender = Context.User.Claims.FirstOrDefault(cl => cl.Type == "username")?.Value;
    return Clients.User(user)
                  .SendAsync("ReceiveMessage", $"Message from {sender}: {message}");
}

这将从当前连接的用户向指定用户发送一条消息.

This sends a message from the currently connected user, to the specified user.

现在,我想向连接的每个用户发送一条单独的消息;类似于以下概念:

Now I'd like to send an individual message to every user connected; something like the following concept:

public Task UpdateMessageStatus()
{
    foreach(client in Clients.Users)
    {
         var nrOfMessages = GetMessageCount();
         client.SendAsync($"You have {nrOfMessages} messages.");
    }
}

我该如何实现?即我该如何遍历连接的用户,并向每个用户发送单独的消息?

How can I achieve this; i.e. how can I iterate over connected users, and send individual messages to each of them?

修改/澄清

如前所述,我需要向每个连接的用户发送个人(即专门的)消息,因此使用Clients.All并不是一种选择,因为只能用于将相同的消息发送给所有已连接的用户.

As mentioned, I needed to send individual (i.e. specialized) messages to each connected user, so using Clients.All was not an option, as that can only be used to send the same message to all connected users.

我最终做的事情与Mark C.在接受的答案中发布的内容相似.

I ended up doing something similar to what Mark C. posted in the accepted answer.

推荐答案

如果您对不使用提供给您的Clients.All API感到困惑,则可以保留连接用户的本地缓存并将其用作您的已连接用户列表.

If you're deadset on not using the Clients.All API that is given to you, you can keep a local cache of the connected users and use that as your list of connected users.

类似这样的东西:

static HashSet<string> CurrentConnections = new HashSet<string>();

    public override Task OnConnected()
    {
        var id = Context.ConnectionId;
        CurrentConnections.Add(id);

        return base.OnConnected();
    }

    public Task SendAllClientsMessage()
    {
        foreach (var activeConnection in GetAllActiveConnections())
        {
            Clients.Client(activeConnection).SendMessageAsync("Hi");
        }
    }

    public override System.Threading.Tasks.Task OnDisconnected(bool stopCalled)
    {
        var connection = CurrentConnections.FirstOrDefault(x => x == Context.ConnectionId);

        if (connection != null)
        {
            CurrentConnections.Remove(connection);
        }

        return base.OnDisconnected(stopCalled);
    }


    //return list of all active connections
    public List<string> GetAllActiveConnections()
    {
        return CurrentConnections.ToList();
    }

这篇关于如何在asp.net核心SignalR中遍历用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆