【问题标题】:SignalR - Update specific user (Push notifications)SignalR - 更新特定用户(推送通知)
【发布时间】:2020-05-10 01:20:39
【问题描述】:

我无法仅更新一个特定用户。

我正在开发一些 asp.net 核心 Web 应用程序,我想为我的项目实现推送通知。我将进一步解释我在我的应用程序中所做的事情。

我有一个页面,用户可以在其中发布内容(例如在 facebook 上)。在那个帖子上,每个人都可以喜欢/不喜欢它(喜欢按钮)或评论它(也可以删除 cmets)。我在该部分的 signalR 实现与await Clients.All.SendAsync("UpdateComments", userId, postId); 完美配合。

现在我想向帖子所在的用户发送通知。 我试图以这种方式做到这一点await Clients.User(userId).SendAsync("SendNotification", notificationText); 但没有工作。当我调试它时,在这部分User(someId) 它希望我发送connectionId 我没有给我想要更新的用户。我只有调用当前连接的用户的 connectionId。

我的问题是:如何使用我的表中的 userId 更新用户,或者如何根据我的 userId 获取 connectionId? 如果我无法做到这一点,有没有一种方法可以在某些 signalR 组连接中自动添加用户(当他登录到应用程序时),而无需用户激活连接他自己?

我用谷歌搜索了很多,但我没有找到答案。 This 是我在我的应用程序中实现 signalR 的链接。

【问题讨论】:

标签: javascript node.js asp.net-core signalr asp.net-core-signalr


【解决方案1】:

我已经在写小博了here

你需要写一个方法来像这样发送到特定的用户 id

  public async Task Send(string userId)
    {
        var message = $"Send message to you with user id {userId}";
        await Clients.Client(userId).SendAsync("ReceiveMessage", message);
    }

然后监听事件

(function () {
        var connection = new signalR.HubConnectionBuilder().withUrl("/connectionHub").build();

        connection.start().then(function () {
            console.log("connected");

            connection.invoke('getConnectionId')
                .then(function (connectionId) {
                    sessionStorage.setItem('conectionId', connectionId);
                    // Send the connectionId to controller
                }).catch(err => console.error(err.toString()));;


        });

        $("#sendmessage").click(function () {
            var connectionId = sessionStorage.getItem('conectionId');
            connection.invoke("Send", connectionId);
        });

        connection.on("ReceiveMessage", function (message) {
            console.log(message);
        });

    })();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-12
    • 1970-01-01
    • 1970-01-01
    • 2017-08-19
    相关资源
    最近更新 更多