使用SignalR推送通知 [英] Push notifications with SignalR

查看:109
本文介绍了使用SignalR推送通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am developing an application in .net core with SignalR. Users will be subscribed to the system. What I need to know is: Does a user have to be logged in to receive a notification? I would like for the notification to be pushed without them having to log in every time. It must be similar to a WhatsApp message that just "arrives". Is this possible with SignalR?

推荐答案

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

Each active tab is one connection to SignalR (the Client), with a unique ConnectionId. Depending on the usage of notifications, a visitor does not have to be logged in. A connection with a SignalR Hub is established when the JavaScript code has been initialized.

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

You can simply invoke (call) a JavaScript function from the server for each Client (visitor). So all visitors will receive the notification:

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

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

All connected clients will receive this 'event' from the server. Write a 'listener' for the ReceiveNotification event inside your JavaScript to do something client side:

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


示例

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

1)通过JavaScript;

1) From the JavaScript;

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

2)使用

2) From the Server (e.g. a controller), using 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 文档.

Example (modified) is taken from the SignalR HubContext documentation.

这篇关于使用SignalR推送通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆