使用SignalR推送通知

Luk*_*ent 0 c# sql-server signalr signalr.client asp.net-core

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

Mat*_*ijs 6

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

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

await Clients.All.SendAsync("ReceiveNotification", "Your notification message");
Run Code Online (Sandbox Code Playgroud)

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

connection.on("ReceiveNotification", function (user, message) {
    // Show the notification.
});
Run Code Online (Sandbox Code Playgroud)

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

1)从JavaScript;

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

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

示例(已修改)取自SignalR HubContext文档。