使用SignalR推送通知

卢克·文森特

我正在使用SignalR在.net核心中开发应用程序。用户将订阅该系统。我需要知道的是:是否必须登录用户才能收到通知?我希望推送通知而无需他们每次都登录。它必须类似于仅“到达”的WhatsApp消息。SignalR是否可能?

马蒂斯

每个活动选项卡都是与SignalR(客户端)的一个连接,带有唯一的ConnectionId根据通知的使用情况,访问者不必登录。初始化JavaScript代码后,便会与SignalR Hub建立连接。

您可以简单地从服务器为每个客户端(访问者)调用(调用)JavaScript函数因此所有访客都会收到通知:

await Clients.All.SendAsync("ReceiveNotification", "Your notification message");

所有连接的客户端将从服务器接收此“事件”。ReceiveNotification您的JavaScript中事件编写一个“侦听器”,以执行客户端操作:

connection.on("ReceiveNotification", function (user, message) {
    // Show the notification.
});

根据您要发送通知的方式,可以调用ReceiveNotification

1)从JavaScript;

connection.invoke("SendMessage", user, message).catch(function (err) {
    return console.error(err.toString());
});

2)从服务器(例如控制器),使用 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文档。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章