1

In my asp.net core 3.1 application I am using signalr for sending messages and angular for UI. So for now Everyone can see messages, I would like to send message only for appropriate organizations can see. For ex: I have 2 organizations, org1 and org2. In org1 there are 4 users and in org2 it is 5 users. I would like to send messages for ex: org1 user loggedin and only 4 users should notified. I have getCurrentOrgId as well.

My NotificationHub Class looks like:

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

And I am using HubContext to send message:

  private readonly IHubContext<NotificationHub> _hubContext;

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

// I would like some organizationGroup and send messages only loggedinuser orgId == getCurrentOrgId. Only users for appropriate organization can see notification orgId2 users should not see orgId1 users notification.

Arzu Suleymanov
  • 671
  • 2
  • 11
  • 33
  • DUPLICATION: https://stackoverflow.com/questions/16167735/signalr-net-client-how-do-i-send-a-message-to-a-group – Ali Dehqan Jul 15 '20 at 13:03
  • Does this answer your question? [SignalR .Net client: How do I send a message to a Group?](https://stackoverflow.com/questions/16167735/signalr-net-client-how-do-i-send-a-message-to-a-group) – Ali Dehqan Jul 15 '20 at 13:04
  • @AliDehqan I tried it is not answer to my question – Arzu Suleymanov Jul 15 '20 at 13:51
  • @ArzuSuleymanov The code i posted doesn't answer you question ? – HMZ Jul 15 '20 at 14:27
  • I think the links and the solution show what you need. You have to put users from each org into a respective group usually done at login. When you send a message it can be done by using _hubContext.Clients.Group(orgId1).SendAsync() – Frank M Jul 15 '20 at 15:09
  • @HMZ problem is I am using IHubContext and I can not access to get ConnectionId – Arzu Suleymanov Jul 15 '20 at 16:08
  • @FrankM in this case I am not getting message in UI, I am using ReceiveMessage keyword for both, for admin role I am sending all messages and it works but as group I am not getting message in UI – Arzu Suleymanov Jul 15 '20 at 16:09
  • @HMZ your way is ok, I accepted answer, but still can not able to get group messaging in UI, maybe in UI something wrong – Arzu Suleymanov Jul 15 '20 at 16:11
  • @HMZ in .net core they changed a lot of things – Arzu Suleymanov Jul 15 '20 at 16:47
  • 1
    @ArzuSuleymanov if you want to send a message to a specific user you can use the `UserId` using `Clients.User(userId).SendAsync()`, you can use a `static` `ConcurrentDictionary` to store groups and users information like connection ids as keys and values, also you can cache the groups and connectionIds in the server cache using the `OnConnected` via a `Dictionary` and then access them outside the hub if you wish. – HMZ Jul 15 '20 at 17:44

1 Answers1

3

This is a sample of what a hub with groups might look like :

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

I have an extra enum in ApplicationUser called UserType which i use to add users to groups on connect.

HMZ
  • 2,949
  • 1
  • 19
  • 30