我已经遵循了有关如何使用信号器通过控制器发送消息的教程。我已经设置了 hubcontext 和方法。然而,通知并没有按应有的方式弹出。我进一步研究发现javascript应该是signalr.js。这是因为我使用的是 ASP.NET Core 框架。我已遵循正确的教程,但通知不起作用。下面是到目前为止我的代码。任何帮助将不胜感激。
成员控制器
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");
通知中心
public class NotificationHub : Hub
{
public async Task SendNotification(string Message)
{
await Clients.All.SendAsync("ReceiveNotification", Message);
}
}
脚本
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());
});
每当我运行应用程序时,我通常也会收到此错误
Uncaught ReferenceError: signalr is not defined
at notification.js:3:22 `
如有任何帮助,我们将不胜感激。 谢谢你。
从错误消息来看,您的项目似乎没有正确添加相关的SignalR JavaScript库。
我创建了一个简单的演示来模拟您的案例。
首先,参考这个Docs添加相关的SignalR库。
中心
public class ChatHub : Hub
{
public async Task SendNotification(string Message)
{
await Clients.All.SendAsync("ReceiveNotification", Message);
}
}
控制器
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");
}
}
查看脚本
var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();
connection.on("ReceiveNotification", function(message){
//........
document.getElementById("all").textContent = message
});
//.......
从上面的 git demo 中,您可以看到当用户创建时,所有用户都可以收到该通知。