Search code examples
c#asp.net-coreasp.net-core-signalr

Notification sending to single user and to admin role users using Signalr in .net core


basicly i did a hub which sends notification when some action happens in repository . I want to change this to signle User sending , for example to send notificaiton if action happened on that user or to send all notifications to the admin role users.

right now i have just a hub and i use

                await _hubContext.Clients.All.SendAsync("displayNotification", "");

and in html side

    const connection = new signalR.HubConnectionBuilder()
        .withUrl("/NotificationHub")
        .configureLogging(signalR.LogLevel.Information)
        .build();

    connection.on('displayNotification', () => {
        getNotification()
        toastr.info("You hava a new Notification");
    }
    );

    async function start() {
        try {
            await connection.start();
            console.log("connected");
        } catch (err) {
            console.log(err);
            setTimeout(() => start(), 5000);
        }
    };

    connection.onclose(async () => {
        await start();
    });

    start();

Solution

  • I want to change this to signle User sending , for example to send notificaiton if action happened on that user or to send all notifications to the admin role users.

    When we call hub methods from outside of the Hub class, there's no caller associated with the invocation. Therefore, we can not use code snippet such as Clients.Caller.SendAsync("ReceiveMessage", user, message) to send a message back to the caller.

    To achieve your requirement of sending message to a specific/signle user, you can create single-user group (a group for signle user), then send a message to that group when you want to reach only that specific user.

    And you can also add all admin users in a group, so that you can push notifications to all admin users by sending message to that group.

    await _hubContext.Clients.Group(groupName_Here).SendAsync("ReceiveMessage", $"{message_here}");  
    

    For more information about "Groups in SignalR", please check: https://learn.microsoft.com/en-us/aspnet/core/signalr/groups?view=aspnetcore-5.0#groups-in-signalr

    Besides, to achieve same requirement, as @Prolog mentioned, you can also map users to ConnectionId(s), then send messages to specific connected clients with following code snippet.

    await _hubContext.Clients.Clients(connectionIds_here).SendAsync("ReceiveMessage", $"{message_here}");