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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.