簡體   English   中英

如何使用 signalr 向 asp.net 內核中的特定組發送消息?

[英]How to send message to specific group in asp.net core using signalr?

在我的 asp.net 核心 3.1 應用程序中,我使用 signalr 發送消息,使用 angular 發送 UI。 所以現在每個人都可以看到消息,我想發送消息只給適當的組織可以看到。 例如:我有 2 個組織,org1 和 org2。 在 org1 中有 4 個用戶,在 org2 中有 5 個用戶。 我想為 ex 發送消息:org1 用戶登錄,只有 4 個用戶應該通知。 我也有 getCurrentOrgId 。

我的 NotificationHub Class 看起來像:

 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); 

// 我想要一些組織組並只發送消息loggedinuser orgId == getCurrentOrgId。 只有相應組織的用戶才能看到通知 orgId2 用戶不應看到 orgId1 用戶通知。

這是帶有組的集線器的示例:

    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中有一個名為UserType的額外enum ,用於在連接時將用戶添加到組中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM