【问题标题】:How to send message to specific group in asp.net core using signalr?如何使用信号器向asp.net核心中的特定组发送消息?
【发布时间】:2020-07-15 19:29:48
【问题描述】:

在我的 asp.net core 3.1 应用程序中,我使用 signalr 发送消息和 angular 用于 UI。 所以现在每个人都可以看到消息,我想发送消息只给适当的组织可以看到。 例如:我有 2 个组织,org1 和 org2。在 org1 中有 4 个用户,在 org2 中有 5 个用户。 我想为 ex 发送消息:org1 用户登录,只有 4 个用户应该通知。 我也有 getCurrentOrgId。

我的 NotificationHub 类如下所示:

 public class NotificationHub : Hub
    {
        public async Task SendMessage(string user, string message)
        {
            await Clients.All.SendAsync("ReceiveMessage", user, message);
        }
    }

我正在使用 HubContext 发送消息:

  private readonly IHubContext<NotificationHub> _hubContext;

  await _hubContext.Clients.All.SendAsync("ReceiveMessage",$"{notificationToAdd.ActionMessage}", cancellationToken: cancellationToken); 

// 我想要一些组织组,并且只发送消息 loginuser orgId == getCurrentOrgId。只有相应组织的用户才能看到通知 orgId2 用户不应看到 orgId1 用户通知。

【问题讨论】:

  • @AliDehqan 我试过它不能回答我的问题
  • @ArzuSuleymanov 我发布的代码没有回答你的问题?
  • @ArzuSuleymanov 如果您想向特定用户发送消息,您可以使用UserIdClients.User(userId).SendAsync(),您可以使用static ConcurrentDictionary 来存储组和用户信息,例如连接 ID 作为键和值,您也可以通过 Dictionary 使用 OnConnected 在服务器缓存中缓存组和连接 ID,然后如果您愿意,可以在集线器外部访问它们。

标签: c# asp.net-core signalr


【解决方案1】:

这是一个带有群组的集线器的示例:

    public class NotificationHub : Hub
    {
        private readonly UserManager<ApplicationUser> userManager;

        public NotificationHub(UserManager<ApplicationUser> userManager)
        {
            this.userManager = userManager;
        }

        public async override Task OnConnectedAsync()
        {
            var user = await userManager.FindByNameAsync(Context.User.Identity.Name);

            if (user != null)
            {
                if (user.UserType == UserType.Administrator)
                {
                    await AddToGroup("Administrators");
                }
                else if (user.UserType == UserType.Employee)
                {
                    await AddToGroup("Employees");
                }
            }
            else
            {
                await Clients.Caller.SendAsync("ReceiveNotification", "Connection Error", 0);
            }
        }


        public async Task SendNotification(string group, string message, int messageType)
        {
            await Clients.Group(group).SendAsync("ReceiveNotification", message, messageType);
        }

        public async Task AddToGroup(string groupName)
        {
            await Groups.AddToGroupAsync(Context.ConnectionId, groupName);
        }

        public async Task RemoveFromGroup(string groupName)
        {
            await Groups.RemoveFromGroupAsync(Context.ConnectionId, groupName);
        }
    }

我在ApplicationUser 中有一个额外的enum,名为UserType,我用它在连接时将用户添加到组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-04
    • 1970-01-01
    • 1970-01-01
    • 2015-07-08
    • 2015-08-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多