我正在使用 SignalR 在 .net 核心中开发应用程序。用户将订阅该系统。我需要知道的是:用户是否必须登录才能收到通知?我希望无需每次都登录即可推送通知。它必须类似于刚刚“到达”的 WhatsApp 消息。 SignalR 可以做到这一点吗?
最佳答案
每个事件的浏览器选项卡都是与 SignalR(客户端)的一个连接,具有唯一的 ConnectionId
.根据通知的使用情况,访问者不必登录。在初始化 JavaScript 代码后,会建立与 SignalR Hub 的连接。
您可以简单地从服务器为每个 Client(访问者)调用(调用)JavaScript 函数。所以所有访问者都会收到通知:
await Clients.All.SendAsync("ReceiveNotification", "Your notification message");
所有连接的客户端将从服务器接收这个“事件”。为 ReceiveNotification
写一个“监听器”你的 JavaScript 中的事件在客户端做一些事情:
connection.on("ReceiveNotification", function (user, message) {
// Show the notification.
});
例子
根据您希望发送通知的方式,您可以调用 ReceiveNotification
:
- 来自 JavaScript;
connection.invoke("SendMessage", user, message).catch(function (err) {
return console.error(err.toString());
});
- 从服务器(例如 Controller ),使用
IHttpContext<THub>
public class HomeController : Controller
{
private readonly IHubContext<SomeHub> _hubContext;
public HomeController(IHubContext<SomeHub> hubContext)
{
_hubContext = hubContext;
}
public async Task<IActionResult> Index()
{
await _hubContext.Clients.All.SendAsync("ReceiveNotifiction", "Your notification message");
return View();
}
}
示例(已修改)取自 SignalR HubContext文档。
关于c# - 使用 SignalR 推送通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53901043/