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

How do I notify clients using notification hub in a controller


I have followed tutorials on how to send messages through a controller using signalr. I have setup the hubcontext and the methods. However, the notices are not popping up as they should. I further researched that the javascript ought to be signalr.js. This is because I am using ASP.NET Core framework. I have followed the right tutorials yet the notifications are not working. Below is my code so far. Any help will be appreciated.

MemberController

 ctx.Members.Add(addThisMember);
            await ctx.SaveChangesAsync();
            notyf.Success("member successfully created.");
            await hCtx.Clients.All.SendAsync("ReceiveNotification", $"New Member added: {addThisMember.Fullname}");
            return RedirectToAction("Members"); 

NotificationHub

    public class NotificationHub : Hub
    {
        public async Task SendNotification(string Message)
        {
            await Clients.All.SendAsync("ReceiveNotification", Message);

        }
    }

Script

    var connection = new signalr.HubConnectionBuilder().withUrl("/NotificationHub").build();

    connection.on("ReceiveNotification", function (message) {
        // do whatever you want to do with `message`

        var li = document.createElement("li");
        document.getElementById("messagesList").appendChild(li);
        li.textContent = `${user} says ${message}`;
    });

connection.start().catch(function (err) {
    return console.error(err.toString());
});

I usually get this error too any time I run the application

  Uncaught ReferenceError: signalr is not defined
    at notification.js:3:22  `

Any help would be appreciated. Thank you.


Solution

  • From the error message, Your project seems not to add related SignalR JavaScript library correctly.

    I create a simple demo to mock your case.

    First, refer this Docs to add related SignalR library.

    enter image description here

    Hub

    public class ChatHub : Hub
        {
            public async Task SendNotification(string Message)
            {
                await Clients.All.SendAsync("ReceiveNotification", Message);
    
            }
        }
    

    Controller

    public class HomeController : Controller
        {
            private readonly ILogger<HomeController> _logger;
            private readonly IHubContext<ChatHub> _chatHub;
    
            public HomeController(ILogger<HomeController> logger, IHubContext<ChatHub> chatHub)
            {
                _logger = logger;
                _chatHub = chatHub;
            }
    
            //...........
    
            public async Task<IActionResult> create()
            {
                await _chatHub.Clients.All.SendAsync("ReceiveNotification", $"New Member added !!!!!!!");
                return RedirectToAction("privacy");
            }
    }
    

    View script

    <script src="~/js/signalr/dist/browser/signalr.js"></script>
    <script src="~/js/chat.js"></script>
    <script>
    
        var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();
        
         connection.on("ReceiveNotification", function(message){
        
                //........
               document.getElementById("all").textContent = message
            });
    
        //.......
    </script>
    

    Gif Demo enter image description here

    From above git demo, you can see when user created, all user can receive that notification.