如何在控制器中使用通知中心通知客户端?

huangapple go评论91阅读模式
英文:

How do I notify clients using notification hub in a controller

问题

我已经按你的要求翻译了代码部分,如下所示:

MemberController

ctx.Members.Add(addThisMember);
await ctx.SaveChangesAsync();
notyf.Success("会员成功创建。");
await hCtx.Clients.All.SendAsync("ReceiveNotification", $"新会员已添加:{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) {
    // 根据需要处理 `message`

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

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

通常情况下,当我运行应用程序时,我也会遇到以下错误:

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

希望这有助于解决你的问题。如果有任何其他问题,请随时提问。

英文:

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.

答案1

得分: 1

从错误消息来看,您的项目似乎未正确添加相关的SignalR JavaScript库。

我创建了一个简单的演示来模拟您的情况。

首先,参考这个文档来添加相关的SignalR库。

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演示

如何在控制器中使用通知中心通知客户端?

从上面的Git演示中,您可以看到当用户创建时,所有用户都可以收到该通知。

英文:

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.

如何在控制器中使用通知中心通知客户端?

Hub

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

        }
    }

Controller

public class HomeController : Controller
    {
        private readonly ILogger&lt;HomeController&gt; _logger;
        private readonly IHubContext&lt;ChatHub&gt; _chatHub;

        public HomeController(ILogger&lt;HomeController&gt; logger, IHubContext&lt;ChatHub&gt; chatHub)
        {
            _logger = logger;
            _chatHub = chatHub;
        }

        //...........

        public async Task&lt;IActionResult&gt; create()
        {
            await _chatHub.Clients.All.SendAsync(&quot;ReceiveNotification&quot;, $&quot;New Member added !!!!!!!&quot;);
            return RedirectToAction(&quot;privacy&quot;);
        }
}

View script

&lt;script src=&quot;~/js/signalr/dist/browser/signalr.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;~/js/chat.js&quot;&gt;&lt;/script&gt;
&lt;script&gt;

    var connection = new signalR.HubConnectionBuilder().withUrl(&quot;/chatHub&quot;).build();
    
     connection.on(&quot;ReceiveNotification&quot;, function(message){
    
            //........
           document.getElementById(&quot;all&quot;).textContent = message
        });

    //.......
&lt;/script&gt;

Gif Demo
如何在控制器中使用通知中心通知客户端?

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

huangapple
  • 本文由 发表于 2023年7月31日 21:16:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76804027.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定